【问题标题】:Different view / method based on middleware using the same route in Laravel基于中间件的不同视图/方法在 Laravel 中使用相同的路由
【发布时间】:2020-11-18 06:19:53
【问题描述】:

我想将登录的用户重定向到'/' 路由(比如example.com,后面没有任何东西)

这行得通:

Route::get('/', Home::class)->name('home');

class Home extends Controller
{
    public function __invoke()
    {
        if(Auth::check()) {
            return view('dashboard');
        }
        else {
            return view('welcome');
        }
    }
}

但是现在我需要在这个路由/控制器中添加中间件。

文档建议将 $this->middleware(['auth', 'verified']) 添加到我的 Home 控制器中的 __constructor。

这不起作用,因为它还会影响来宾的视图 (return view('welcome');)

我也试过了:

Route::get('/', [Home::class, 'index'])->name('home');

class Home extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth', 'verified'])->only('dashboard');
    }
    
    public function index()
    {
        if(Auth::check()) {
            $this->dashboard();
        }
        else {
            $this->welcome();
        }
    }
    
    public function welcome()
    {
        return view('welcome');
    }
    
    public function dashboard()
    {
        return view('dashboard');
    }
}

但这也不起作用。有什么想法吗?

【问题讨论】:

  • 要使用Auth,需要中间件auth
  • 为什么不能是两条不同的路线?
  • @lagbox 当您转到facebook.com 时,您会看到一个登录/注册表单。登录后,您将被重定向到相同的 URL:facebook.com。我想在我的应用程序中使用同样的东西。

标签: laravel routes laravel-fortify


【解决方案1】:

我在谷歌搜索类似的东西时发现了这个问题,所以我为这些人写这个,对不起。

这看起来像是我不熟悉的非常旧的 Laravel 版本(并且可能不再受支持),所以我将为 Laravel 9 给出答案。

要返回不同的视图,具体取决于它们是否已登录,请使用

// routes/web.php

Route::get('/home', function() {
    if (Auth::check()) {
        return view('dashboard');
    } else {
        return view('welcome');
    }
});

如果必须使用其他一些策略的结果并调用控制器方法,请使用

// routes/web.php

use App\Http\Controllers;
use Illuminate\Support\Facades\Gate;

Route::get('/settings', function () {
    if (Gate::allows('manageSystem')) {
        return (new Controllers\SettingsController)->index();
    } else {
        return (new Controllers\UserController)->settings();
    }
});

我没有更改来测试这个,但我希望这对某人有帮助

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2018-10-20
    • 2018-09-10
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多