参考:https://devnote.in/laravel-simple-role-based-authentication/
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.
<?php
#app\Http\Middleware\IsAdmin.php
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.
#app\Http\Kernel.php
/**
* 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.
<?php
#app/routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('home', [DashboardController::class, 'index'])->name('home');
Route::group(['middleware' => ['admin']], function () {
Route::get('product', [DashboardController::class, 'products'])->name('product.index');
});
评论