Home > PHP Framework > Laravel > 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

藏色散人
Release: 2020-08-13 11:53:21
forward
3025 people have browsed it

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.
Copy after login

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

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

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,   // 这一行
    ];
Copy after login

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

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

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template