Alphy Gacheru
Alphy Gacheru

Reputation: 657

How to paginate a relationship result in laravel

How do you paginate the following line

$posts = Category::where('name', request('category'))->firstOrFail()->posts;

in the function below

public function index()
    {
        $categories = category::all();

        if (request('category')) {
            $posts = Category::where('name', request('category'))->firstOrFail()->posts;

        } else {
            $posts = post::where('status', 1)->orderBy('created_at', 'DESC')->paginate(5);
        }


        return view('user.blog', compact('posts', 'categories'));
    }

Upvotes: 0

Views: 1520

Answers (1)

Dan
Dan

Reputation: 5358

You have to use the actual relationship method to get access to the query builder:

$posts = Category::where('name', request('category'))
    ->firstOrFail()
    ->posts()
    ->paginate(5);

See the Eloquent docs on Relationship Methods Vs. Dynamic Properties for reference.

Upvotes: 2

Related Questions