Laravel路线-相同路线,不同控制器 [英] Laravel Routes - Same route, different controllers

查看:61
本文介绍了Laravel路线-相同路线,不同控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网络应用程序上添加一个功能,让用户访问相同的 URL 并根据他们是否登录来获取不同的页面.我现在这样做的方法是使用中间件将登录的用户重定向到/home.但是,我想做类似Facebook的事情.

I want to add a functionality on my web app where users visit the same URL and get different pages depending if they are logged in or not. The way I'm doing this now is using a middleware to redirect logged in users to /home. But, I want to do something like facebook does..

当某人键入 http://facebook.com 时,它将分析该人是否已登录,是否已登录.,它会显示他们的住所,如果不是,则会显示在同一URL上的注册页面(您可以看到栏中的地址没有更改)

When someone types http://facebook.com, it analyzes if the person is logged in, if they are, it shows their home, if they are not, it shows the registration page on the same URL (you can see that the address in the bar does not change)

我正在尝试在路线上使用此代码:

I'm trying to use this code on my route:

Route::get('/', array('as'=>'home', 'uses'=> (Auth::check()) ? "usercontroller@home" : "homecontroller@index" ));

在这里找到: https://stackoverflow.com/a/18896113/2724978

但是无论用户是否登录,它仅显示第二种控制器方法("homecontroller @ index").

But it just shows the second controller method ("homecontroller@index") no matter if the user is logged in or not.

推荐答案

是@AJReading建议并使用普通的控制器方法来处理吗?

Is it just me or can't you just do as @AJReading has suggested and use an ordinary controller method to handle this?

设置如下:

在您的 HomeController.php 中:

class HomeController extends Controller
{
    /**
     * Show a different view depending on whether or not the user is logged-in.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (Auth::check()) {
            // logged-in
            return view('home.index.authorised')->with('user', Auth::user());
        } else {
            // not logged-in
            return view('home.index.guest');
        }
    }
}

然后创建您的备用视图,例如resources/views/home/guest.blade.php

Then create your alternate views e.g. resources/views/home/guest.blade.php

这篇关于Laravel路线-相同路线,不同控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆