Laravel simple role-based authentication

By admin, 18 五月, 2023


Now Create a middleware to handle auth admin roles.

php artisan make:middleware IsAdmin

Now open IsAdmin.php the file in your project middleware directory.


namespace App\Http\Middleware;

use Closure;
use Auth;

class IsAdmin
     * Handle an incoming request.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if (Auth::user() &&  Auth::user()->is_admin == 1) {
            return $next($request);

        return redirect('home')->with('error','You have not admin access');

And open kernel.php the file and go to the protected $routeMiddleware property and update the admin middleware.

     * The application's route middleware.
     * These middleware may be assigned to groups or used individually.
     * @var array
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'admin' => \App\Http\Middleware\IsAdmin::class, //added

Step 6: Add Middleware Route

Now we will create one route, which protected the admin, and if the user is not an admin, then it will redirect to the home page. otherwise, he can access this page.


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;

Route::get('/', function () {
    return view('welcome');


Route::get('home', [DashboardController::class, 'index'])->name('home'); 
Route::group(['middleware' => ['admin']], function () {
   Route::get('product', [DashboardController::class, 'products'])->name('product.index');




Restricted HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <img src>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.