S
S
Sergey Chazov2019-04-06 00:00:03
Laravel
Sergey Chazov, 2019-04-06 00:00:03

How to make pagination with a many-to-many relationship?

There is a companies table, a users table, and a company_user table.
On the page, I display the companies that the current authorized user consists of:

$userID = Auth::user()->id;
$user = App\User::find($userID);
$companies=$user->companies;
@foreach($companies as $company)
{{ $company->name }}
@endforeach

I need to make a paginator to this output.
It doesn’t work at all ... I tried it like this - it doesn’t work:
$companies2=App\Company::withCount(['users' => function ($query) {
    $query->where('id', auth()->id());
}])->paginate(1);

Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2019-04-06
@chazovs

$user->companies()->paginate(10)
In general, it is easier and more understandable not to use a relation in this case. It still doesn't make much sense.
Just App\Company::where('user_id', $user_id)->paginate(10);
Some kind of porridge turned out here, why not just where?

withCount(['users' => function ($query) {
    $query->where('id', auth()->id());
}])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question