Home > OS >  Protect Route in Laravel 9 Based on User Column Value
Protect Route in Laravel 9 Based on User Column Value

Time:04-19

I have a column in my User table named role with 2 possible values--"Admin" and "Driver". All my crud routes are protected with Auth middleware but I'd like to further secure a few of those routes. For example I'd like to have the "Create" routes only accessible by Users with the role column equalling "Admin". I wasn't sure how to go about this so I can't provide examples of what I've tried.

web.php

...
Route::middleware(['auth', 'verified'])->group(function () {
    Route::get('/users', App\Http\Livewire\User\Index::class)->name('users.index');
    Route::get('/user/{user}/edit', App\Http\Livewire\User\Edit::class)->name('user.edit');

    /* This is the route I want to protect to just "Admin" role */
    Route::get('/user/create', App\Http\Livewire\User\Create::class)->name('user.create');
...

CodePudding user response:

You can create a middleware with the artisan command

php artisan make:middleware IsAdminMiddleware

Then add something like this in the handle function of your middleware.

public function handle(Request $request, Closure $next)
{
  // This validation assumes you can access role from User Model
  if ($request->user()->role != "Admin") {
     return response()->json(['error' => 'you are not an admin!'], 403);
  }

  return $next($request);
}

Finally add the middleware on your Routes

Route::get('/user/create', App\Http\Livewire\User\Create::class)
  ->middleware(IsAdminMiddleware::class) // <<----
  ->name('user.create');

For more info refer to middleware the docs at laravel.

CodePudding user response:

You can use authorization in laravel for your case

in laravel you can use gate or policy for further feature

https://laravel.com/docs/9.x/authorization

Gate

define gate in App\Providers\AuthServiceProvider on method boot

use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Access\Response;
use App\Models\User;
/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();
 
    Gate::define('create', function (User $user) {
        return ($user->role == 'Admin')
            ? Response::allow()
            : Response::deny('You must be an administrator.');
    });
}

On your controller

<?php
 
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
 
class CreateController extends Controller
{
    public function create(Request $request)
    {
        $user = Auth::user();
        if (Gate::allows('create', $user)) {
            //create 
        }

    }
}
  • Related