You're using get instead of paginate.
Jul 28, 2018
11
Level 2
Pagination on Eager Load
The following works, but returns a Collection, not a Paginator. Any ideas on how to get the Paginator?
$users = User::with([
'books' => function($query) use ($orderby, $search){
$query
->where('books.title', 'LIKE', '%'. $search .'%')
->orWhere('books.isbn', 'LIKE', '%'. $search .'%')
->orderby($orderby, 'asc')
->paginate(5);
}
])->where('id', $user_id)->get();
Level 43
https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
The docs show the similar example clearly:
class User extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
$roles = App\User::find(1)->roles()->orderBy('name')->get();
So second query operates on a Books rather than intermediate table. So title and ISBN constraints are applied to the books table.
To get immediate (pivot) model, for example let's say you want to see the date user has returned a book you would make a returned_at date at the book_user table and call it:
@foreach ($user->books()->where(...)->get() as $book)
{{ dd($book->pivot->returned_at) }}
@endforeach
1 like
Please or to participate in this conversation.