Search code examples
laravelmiddlewarelaravel-6

Only roles that are Admins can have access to /admin. But its not working


User.php:

public function IsAdmin(){
    return $this->role=='admin';
}

Checkifadmin.php (middleware):

public function handle($request, Closure $next)
{
  if (auth()->user()->role=='admin') {
    return redirect(route('home'));
  }
  return $next($request);
}

Kernel.php :

In protected routes

'checkifadmin' =>\App\Http\Middleware\Checkifadmin::class,

create_users_table.php

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('role')->default('customer');
            $table->rememberToken();
            $table->timestamps();
});

web.php:

Route::get('admin',function(){
return view('layouts.admin');
})->middleware(['checkifadmin']);
Route::get('/', function () {
    return view('index');
})->name('home');
Route::get('/shop/product', function () {
    return view('shop.product');
})->name('shop.product');
Route::get('/shop/shoppingcard', function () {
    return view('shop.shoppingcard');
})->name('shop.shoppingcard');
Route::get('/shop/checkout', function () {
    return view('shop.checkout');
})->name('shop.checkout');

Auth::routes();

I have 2 roles in my user. Customer and admin, only admins should have access to /admin but it does not seem to work for some reason. I have copy and pasted every possible code that i have made regarding to this matter, thank u in advance


Solution

  • Middleware should be like follow if only admin are allowed in

    Checkifadmin.php (middleware):

    public function handle($request, Closure $next)
    {
        if (auth()->user()->role !='admin') {
            return redirect(route('home'));
        }
    
        return $next($request);
    
    }
    

    Then you can keep your route as is

    Route::get('admin',function() {
        return view('layouts.admin');
    })->middleware(['checkifadmin']);