Search code examples
laraveleloquentmany-to-manypivotrelationships

How to limit access from pivot table? Laravel


I have tables:

user

  • id
  • name

companies

  • id
  • name

company_user

  • company_id
  • user_id

Tables has Many To Many relationships.

As it complicated relationship for me, I can't find way how to make this limit, when user can see companies that was created by this user. (probably not well experienced)

Now I have this, but user can see any company

CompanyController:

public function show($company_id)
{
    $company = Company::where('id', $company_id)->firstOrFail();

    return view('company.settings', compact('company'));
}

So tip me please how to make user can see only companies created by this user.


Solution

  • You can do this:

    public function show($company_id)
    {
        $company = auth()->user()->companies()->findOrFail($company_id);
        return view('company.settings', compact('company'));
    }
    

    It will scope the company to the currently logged in user (through the many-to-many relationship on the User model). If none is found, it will return 404.