Query Scopeはoperationのショートカット機能
e.g. latest
public function index()
{
$posts = Post::latest()->get();
// return $posts;
return view("posts.index", compact('posts'));
}
order by created desc | ascと一緒です。
$posts = Post::orderBy('id', 'desc')->get();
qeuryScopeを自作する
Model: Post.php
public function static scope.${functionName}がコンベンション。${functionName}はcamelCaseで書く
public static function scopeLatest($query){
return $query->orderBy('id', 'desc')->get();
}
PostsController
public function index()
{
$posts = Post::latest();
// return $posts;
return view("posts.index", compact('posts'));
}
queryのインクルード機能のようなものか。