用户:: find($ user_id)的Laravel分页问题

时间:2018-12-06 20:20:10

标签: php laravel pagination

我在Laravel中获得了这段代码:

public function index()
{
    $user_id = auth()->user()->id; // gets the current user id
    $user = User::find($user_id); // find the specific user id

    $validPosts = $user->posts->paginate(5)->whereIn('status', ['Pending', 'Processing']);
    return view('home', compact('validPosts'));
}

我想返回所有status待处理的帖子,并进行分页处理,其值为5,但出现以下错误:

  

方法Illuminate \ Database \ Eloquent \ Collection :: paginate不   存在。

我知道我在$user->posts->paginate(5)某个地方失败了。

我该怎么办?

2 个答案:

答案 0 :(得分:4)

分页方法适用于Eloquent模型。检索模型,首先应用whereIn,然后再对其进行分页。试试这个:

public function index() {
    $user = auth()->user();
    $validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);

    return view('home', $validPosts); 
}

现在在“主”视图文件中,您可以使用$ validPosts

答案 1 :(得分:0)

您可以尝试这种方式

public function index()
{
    $user_id = auth()->user()->id; // gets the current user id
    $user = User::find($user_id); // find the specific user id


    // paginate function should be last
    $validPosts = $user->posts()->whereIn('status', ['Pending', 'Processing'])->paginate(5);


    // if you want to pass more variable, do it like this
    return view('home', ['validPosts' => $validPosts]);
}

或者您可以这样做

public function index()
{
    $user_id = auth()->user()->id; // gets the current user id 


    // paginate function should be last
    $validPosts = Post::where('user_id', $user_id)->whereIn('status', ['Pending', 'Processing'])->paginate(5);


    // if you want to pass more variable, do it like this
    return view('home', ['validPosts' => $validPosts]);
}

希望这对您有所帮助。