laravel 加中间件的方法 防止直接打开后台

时间:2022-07-02 16:13:53

路由 routes.php

Route::group(['middleware' => ['web','admin.login.login']], function () {

      //后台首页路由
Route::get('/admin/index/index','Admin\IndexController@index');
});

kernel.php

 protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin.login.login' => \App\Http\Middleware\AdminLogin::class, ];

artisan 创建中间件 cmd命令行中

php artisan make:middleware AdminLogin

Middleware AdminLogin.php

<?php

namespace App\Http\Middleware;

use Closure;

class AdminLogin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(!session('user')){
return redirect('admin/login/login');
}
return $next($request);
}
}