Laravel:从带有分页或不分页的控制器中的索引方法获取数据

我正在使用paginate()方法在控制器的index方法中获取分页数据,但有时我需要完整的数据,所以我编写了这样的代码。

public function index(Request $request)
{
    if ($request->page === 'all') {
        $posts = Post::all();
    } else {
        $posts = Post::paginate(10);
    }

    return response([
        'posts' => $posts
    ],Response::HTTP_OK);
}

因此,如果要获取所有数据,我将页面值作为all发送。 如果我想要分页数据,则将页面值发送为integer

它工作正常,但只是想知道是否还有其他更好的方法?

caoxingxiecan 回答:Laravel:从带有分页或不分页的控制器中的索引方法获取数据

您可以进一步简化正在使用的代码。

public function index(Request $request)
{
    $page = $request->page;
    return response([
        'posts' => $page === 'all' ? Post::all() :  Post::paginate($page)
    ],Response::HTTP_OK);
}
,

避免多次加载模型实例。

public function index(Request $request)
{
  $post = Post::query();
  $data = ($request->page === 'all') ? $post : $post->paginate(10);
  return response()->json(['posts' => $data],200);
}
本文链接:https://www.f2er.com/3162710.html

大家都在问