'laravel using policy with many to many relationship pivot table
how do you set policy in many to many relationship since it is using pivot table ||laravel version 6|| Example:MainTable[company and user] PivotTable[company_user]
using view policy as example:
public function view(User $user,Company $company)
{
return $user->companys()->company_id == $company->id;
}
rules: (only the user that belongs to a company can view ) At the moment above code is not working i cannot find example in google or at the documentation it self since most of example is Post and User which they dont consist of pivot table ..
Solution 1:[1]
You could use combination of pluck()
and contains()
collection methods.
public function view(User $user, Company $company)
{
return $user->companys->pluck('id')->contains($company->id);
}
Pluck: https://laravel.com/docs/6.x/collections#method-pluck
Contains: https://laravel.com/docs/6.x/collections#method-contains
Update
Was going through my old answers and decided to make a change to this answer.
firstWhere()
is more efficient for this task.
public function view(User $user, Company $company)
{
return $user->companys->firstWhere('id', $company->id);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |