简体   繁体   中英

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 ..

You could use combination of pluck() and contains() collection methods.

public function view(User $user, Company $company)
{
    return $user->companys->pluck('id')->contains($conpany->id);
}

Pluck: https://laravel.com/docs/6.x/collections#method-pluck

Contains: https://laravel.com/docs/6.x/collections#method-contains

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM