Search code examples
phplaraveleloquentlaravel-authentication

how can I restricted route for vendor who is not approved in laravel?


I have 3 types of users Admin, Vendor, Customer in my laravel E-commerce.

Now I have to restrict routes for those vendors who are not approved by admin. Can someone please tell me the process, please?

here are the two tables users and shops.

users have those attributes

id, name, password, email, phone

and shops have

shop_name, address, shop_phone, owner_id (this is a foreign key of users.id), is_approved(bool)
  • users hasOne shop relation are given here.

Now I need to know How can I restrict all auth routes who are not approved means is_approved==0 for shops.

Can Anyone please help me?


Solution

  • Create a middleware:

    php artisan make:middleware CheckIsApproved
    

    A new middleware class will be created in app/Http/Middleware/CheckIsApproved.php fille.

    Then in thehandle method of the middle, you can do the check:

    public function handle ($request, Closure $next)
    {
        if (auth()->user()->shop->is_approved) {
            return $next($request);
        }
    
        return back()->with('error', 'Unauthorized');
    }
    

    (You may need to customize the condition in theif according to the relationship)

    In the file app/Http/Kernel.php, register the middleware: search $routeMiddleware property and add:

    protected $routeMiddleware = [
        //...
        'isApproved' => \App\Http\Middleware\CheckIsApproved::class,
    ];
    

    Then, in your route definition, you can specify the middleware:

    Route::get('/some-route', 'SomeRouteController@show')->middleware('isApproved');
    

    Check the docs for more insight