首页 文章

如果用户未使用中间件进行身份验证,则Laravel 5.4将重定向到特定页面

提问于
浏览
0

我想将用户(如果未经过身份验证)重定向到我的索引页面(这是登录页面)

似乎无法使它工作,我真的与路由混淆 .

HomeController

class HomeController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return redirect()->guest('/');
    }
}

路由

// Index
Route::get('/', [
    'as' => 'index',
    'uses' => 'UserController@index'
]);

UserController

您看到的路由重定向到 User Controller 函数 User Controller ,如下所示:

*有 __construct() 所以它使用中间件'auth' .

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

public function index(){

    // If user is logged
    if(Auth::check()) {

        // If user has NOT submitted information form redirect there, otherwise to categories
        if(!Auth::user()->submitted_information)
            return redirect()->route('information');
        else
            return redirect()->route('categories');
    }
    else
        return view('index', ['body_class' => 'template-home']);

}

Handler.php

而auth中的 unauthenticated function 内部中间件(Exceptions / Handler.php)

protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->route('index');
    }

我现在得到的错误如下:

InvalidArgumentException in UrlGenerator.php line 304:
Route [index] not defined.

发生此错误的原因在于

return redirect()->route('index'); 在上面的 unauthenticated 函数中 .

我在这里缺少什么?如果您需要更多信息,请随时提出 .

EDIT :到现在为止,如果我从 UserController 删除 __construct() 方法,并在 web.php 中插入 middleware 要使用的所有路由,它就可以了 .

例如

Route::get('/categories', [
    'as' => 'categories',
    'uses' => 'UserController@showCategories'
])->middleware('auth');

但我试图找到,而不指定使用什么中间件,自动使用它 .

3 回答

  • 1

    你的路线应该是这样的

    //索引

    Route::get('/','UserController@index')->name('index);
    

    see here了解有关路由的更多信息 .

  • 3

    尝试

    Route::get('/','UserController@index',['middleware'=>'auth'])->name('index);
    
  • 1

    Build 你的路线,如下面的代码:

    Route::group(['middleware' => ['auth']], function() {
         // uses 'auth' middleware
         Route::resource('blog','BlogController');
    });
    

    Route :: get('/ mypage','HomeController @ mypage');

    打开名为RedirectIfAuthenticated的中间件类,然后在处理函数中编写以下代码:

    if (!Auth::check()) {
         return redirect('/mypage'); // redirect to your specific page which is public for all
    }
    

    希望它对你有用 .

相关问题