簡體   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