Laravel includes Carbon. But to add to another project using composer, do composer require nesbot/carbon
.
Dates
use Carbon\Carbon;
Route::get('/dates', function(){
$date = new DateTime('+1 week');
echo $date->format('m-d-Y');
echo '<br>';
echo Carbon::now()->addDays(10)->diffForHumans();
echo '<br>';
echo Carbon::now()->subMonths(5)->diffForHumans();
echo '<br>';
echo Carbon::now()->yesterday();
});
Accessors
Route::get('/getname', function(){
$user = User::find(1);
echo $user->name;
});
Update your User model to manipulate the output anytime the user’s name is used. Format here is important, needs to start with get, then the attribute name and then the word attribute.
public function getNameAttribute($value) {
return strtoupper($value);
}
Mutators
Mutators will manipulate the data before its sent to the database.
public function setNameAttribute($value) {
$this->attributes['name'] = strtolower($value);
}
Add to route:
Route::get('/setname', function(){
$user = User::find(1);
$user->name = 'William';
$user->save();
});
Now if you check the database after visiting setname, you should see william is in lowercase.
Query Scope
The usual way to query is to do something like this (open PostController):
public function index()
{
$posts = Post::orderBy('id','desc')->get();
return view('posts.index', compact('posts'));
}
Instead we are going to make orderBy shorter by adding a function to our Post model for queries.
public static function scopeMeek($query) {
return $query->orderBy('id','desc')->get();
}
Update PostController:
public function index()
{
$posts = Post::meek();
return view('posts.index', compact('posts'));
}