【问题标题】:laravel 6 route issue when try to redirect尝试重定向时的laravel 6路由问题
【发布时间】:2020-06-15 17:19:20
【问题描述】:

当有人在 URL 中点击主页时,我试图重定向到登录页面,但总是会出现类似

的错误

路由 [admin/login] 未定义。

许多问题都存在相同的问题,但没有解决问题。

如果直接输入 URL,同样的路由也可以工作,但是从 Authenticate.php 重定向不起作用。

routes/web.php

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();
// Admin Routes

// Without auth
Route::group(['prefix' => 'admin', 'namespace' => 'Auth'], function () {
  Route::get('/login', 'AdminLoginController@login');

});



Route::group(['prefix' => 'admin', 'namespace' => 'Auth', 'middleware' => 'auth:admin'], function () {

  Route::get('/home', 'AdminLoginController@home');

});

Authenticate.php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {

            if ($request->is('admin') || $request->is('admin/*')) {
                return route('admin/login');
            } else if ($request->is('vendor') || $request->is('vendor/*')) {
                return route('vendor/login');
            } else {
                return route('login');
            }


        }
    }
}

【问题讨论】:

    标签: php laravel laravel-6 laravel-6.2


    【解决方案1】:

    你没有命名你的路线,所以你不能这样称呼它们,你需要使用:

    Route::group(['prefix' => 'admin', 'namespace' => 'Auth'], function () {
       // just add the name to the route to call route('login')
       Route::get('/login', 'AdminLoginController@login')->name('login');
    });
    

    然后你可以调用:

    return route('login');
    

    或者,如果您不想命名路线,请改用:

    return redirect('admin/login');
    

    编辑:

    我的错,你使用redirectTo函数,所以你只需要返回一个字符串,使用这个:

    return 'admin/login';
    

    【讨论】:

    • 我试过 return redirect('admin/login'); 但它给出了 ErrorException 标头可能不包含多个标头,检测到新行
    • 看我的编辑,我没看到你在使用redirectTo()函数,在这种情况下只返回一个字符串
    • 但是你应该使用路由名称,然后使用route() 函数,它返回一个字符串,这样你可以更灵活地使用你的URI。如果没问题请采纳答案
    • 是的,我是 laravel 的新手,所以我正在学习,请您对多身份登录提供任何建议,例如我有多个登录,例如管理员、供应商、用户。所以我正在使用的方法以及我必须改变的任何东西然后请建议我。
    猜你喜欢
    • 1970-01-01
    • 2017-04-17
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 2018-12-27
    相关资源
    最近更新 更多