oldskool
oldskool

Reputation: 1

How to add pagination to relation in laravel 7 controller?

How can I add pagination to model relation in my controller? Here's my case :

public function show($movie) {
       $movie = Movie::find($movie);
       $episodes = $movie->episodes;
       $genre = $movie->genre;

       return view('layout.detailMovie', compact('movie', 'episodes', 'genre'));
}

I want to add pagination for the $episodes. Where do I have to put the "->paginate()" code?

Upvotes: 0

Views: 417

Answers (2)

iAmGroot
iAmGroot

Reputation: 868

public function show($movie) {
       $movies = Movie::with('episodes', 'genre')->where('movie', $movie)->paginate(3);

       return view('layout.detailMovie', compact('movies'));
}

In Blade

{{ $products->links() }}  OR {{ $products->render() }}

You can fetch data in blade like

foreach($movies as $movie) {}
   //your code
}


foreach($movies->episodes as $episodes) {}
   //your code
}

foreach($movies->genre as $genre) {}
   //your code
}

Upvotes: 1

milad hedayatpoor
milad hedayatpoor

Reputation: 636

try this :

Movie::find($movie)->with('episodes')->paginate(3);

or:

$reports = User::find($user->id)
        ->reports()
        ->orderBy('created_at', 'DESC')
        ->paginate($paginate);
    return $reports;

if that doesnt work look at this : How to paginate a "has many" relationship that is ordered?

Upvotes: 0

Related Questions