Home > front end >  Laravel relationship filter by company_id
Laravel relationship filter by company_id

Time:10-31

I am doing a laravel api with custom permissions feature. This is my structure of tables:

User
id | email | password

Company
id | companyName

Permissions
id | name

User_has_permissions
user_id | company_id | permission_id

I am get the user and permissions with code below in model:

public function permissions() {
    return $this->belongsToMany(Permission::class, 'user_has_permission', 'user_id', 'permission_id');
}

And in controller:

public function show($company_id, $user_id) {
    //now I need return only permissions related with $company_id
    return User::with(['permissions'])->find($User_id);
}

Now, I am need get the user and your permissions, but, only related by company_id.

Anyone have any idea how can I get this result?

Any idea is welcome.

Thanks a lot.

CodePudding user response:

You can query with includes, by doing key value syntax as the parameter. In BelongsToMany, it inner joins with the pivot table, which would make it possible to add a condition on the comapny_id.

return User::with(['permissions' => function ($query) use ($company) { 
    $query->where('user_has_permission.company_id', $company->id);
}])->find($id);
  • Related