Conixs
126
10
Laravel

How to allow only admins to access specific pages?

Posted 6 days ago by Conixs

Hello everyone!

I have a home that shows a dashboard with all my client informations, but each client can just see his own dashboard. To achieve it, I have done the below:

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return Renderable
     */
    public function index()
    {
        if(auth()->user()->isAdmin()) {
            $companies = Company::withTrashed()->orderBy('name')->paginate(8);
            $operations = Operation::paginate(10);

            return view('home', [
                'companies' => $companies,
                'operations' => $operations
            ]);
        } else {
            $company = Company::find(auth()->user()->contributor->company->id);
            $operations = Operation::where('company_id', auth()->user()->contributor->company->id)->paginate(10);

            return view('companies.show', [
                'company' => $company,
                'operations' => $operations
            ]);
        }
    }
}

Also, I have added to AuthServiceProvider:

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot(Gate $gate)
    {
        $this->registerPolicies();

        $gate->before(function ($user) {
            return $user->isAdmin();
        });
    }
}

However, now I need to find a way to block the access to the routes that are exclusive to admins. Therefore, to be able to achieve it, do I need to create policies for each model?

The routes are:

  • carriers
  • companies
  • operations
  • users
  • shifts
  • vehicles

The client can just have access to his own company, own profile and the operations realized in his company.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.