Massimo Lavermicocca
Massimo Lavermicocca

Reputation: 175

Search in many to many relation Laravel

In Laravel I have this models:

class User {
        public function sites(){
                 return $this->belongsToMany(Site::class);
        }
}

and

class Site extends Model {
        public function users(){
                 return $this->belongsToMany(User::class);
        }
}

In DB after migrations I have the table site_user with fields: user_id and sites_id. Now, how can I retrieve for each users the sites al linked to him?

Thanks for the reply.

Upvotes: 0

Views: 653

Answers (2)

Ian
Ian

Reputation: 590

Use eager loading

$users = App\User::with('sites')->get();

Upvotes: 4

Prashant Barve
Prashant Barve

Reputation: 4315

Please check the link below you need to pass the method name on query like below:

$users = App\Users::with('sites')->get();

for more information please visit:

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

also this will help you to reduce the load on your query.

Upvotes: 3

Related Questions