Home  >  Article  >  PHP Framework  >  How to use middleware in laravel to prevent non-logged in users from accessing the page

How to use middleware in laravel to prevent non-logged in users from accessing the page

藏色散人
藏色散人forward
2020-08-13 11:53:212954browse

The following tutorial column of Laravel will introduce to you how laravel uses middleware to prevent non-logged-in users from accessing the page. I hope it will be helpful to friends in need!

How to use middleware in laravel to prevent non-logged in users from accessing the page

1. Generate middleware

[root@localhost MRedis]# php artisan make:middleware CheckLogin
Middleware created successfully.

2. Implement middleware in app\http\middleware\CheckLogin.php

public function handle($request, Closure $next)
    {
        if (!session('user')) {
            return redirect('login');
        }
        return $next($request);
    }

3. Register middleware. Under app\http\kernel.php, add the last line

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'check.login' => \App\Http\Middleware\CheckLogin::class,   // 这一行
    ];

4. Use middleware (be sure to put the login route outside)

Route::group(['middleware' => 'check.login'], function() {内部为,不想让未登录用户进的路由}

5. Success

The above is the detailed content of How to use middleware in laravel to prevent non-logged in users from accessing the page. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete