繁体   English   中英

Laravel 方法 Auth 用户重定向以使用消息登录

[英]Laravel method Auth user redirect to login with message

我想在登录时使用消息重定向访客,但方法:

Auth::user(); 

仅在没有消息的情况下重定向页面登录。 如何添加消息?

示例:

redirect()->route('login')->with('error', 'Please auth!!');

您可以使用执行重定向的中间件来做到这一点。 app/Http/Middleware/Withmessage.php创建中间件,并在StartSession字符串后添加到app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        ...
        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\Withmessage::class, // <-- here
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        ...
    ],
    ...
];

中间件的代码只包含一个字符串,这与干净的中间件不同。

namespace App\Http\Middleware;

use Closure;
use Auth;

class Withmessage {

    public function handle($request, Closure $next)
    {
        $route = $request->route()->getName();
        if(!Auth::user() and $route === 'button-click-button') {                
            return redirect()->route('login')->with('error', 'Please auth!!');
        }

        return $next($request);
    }
}

return redirect('/login')->with('msg','电子邮件或密码不匹配');

您可以将以下内容添加到您的控制器中:

public function __construct()
{
    $this->middleware('auth');
}

您也只能使用一种方法来检查身份验证

public function __construct()
{
    $this->middleware('auth')->only('nameOfMethod');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM