To paginate Eloquent query results in Laravel, you can make use of the paginate()
method provided by Laravel's query builder.
Here's an example:
paginate()
method:use App\Models\User;
public function index()
{
$users = User::paginate(10);
return view('users.index', compact('users'));
}
links()
method provided by Laravel. It will automatically generate the pagination links for you:@foreach ($users as $user)
// Display user information
@endforeach
{{ $users->links() }}
This will display the paginated results with a default of 10 records per page. The paginate()
method automatically adds page number and next
/previous
links.
You can customize the number of records per page by passing a different value to the paginate()
method:
$users = User::paginate(15); // Display 15 records per page
You can also customize the appearance of the pagination links by passing options to the links()
method. For example:
{{ $users->links('pagination.custom') }} // Use a custom pagination view
{{ $users->links('pagination::bootstrap-4') }} // Use Bootstrap 4 pagination style
That's it! Your query results will now be paginated.