Search code examples
phplaravelrouteslaravel-6laravel-authorization

How to create a route in Laravel based on user type?


Based on a User model and table already created, what is the best practice to create a route based on user type?

Usertype is a model and table field.

Does Gates and/or Policies are the best practice?

Eg.: If an authenticated user is an admin user, it can access some views, if the user is a non-admin, it can access other views.

There are many links on the internet, but I can not find "the one".


Solution

  • If the different views have many elements in common, maybe it would be a good idea to create a view as the template, and then other views extending that template, setting their different parts as blade sections.

    {{-- Template --}}
    <span>The view</span>
    <div>
       @yield('content')
    </div>
    
    {{-- One of the views --}}
    @extends('template')
    @section('content')
       <span>Specific content</span>
    @endsection
    

    If the content presented in each view is completely different, it might be a good idea to have one controller method for each one. Then, for the one route use a closure to decide which controller method gets called depending on the criteria you need.

    Route::get('/products/{product}', function (Product $product) {
        $method = Gate::allows('view_details', $product) ? 'viewDetails' : 'viewGeneralInfo';
        return app('ProductController')
            ->callAction($method, ['product' => $product]);
    });