Laravel 4:基于身份验证状态的单个URI的两个不同视图页面 [英] Laravel 4: Two different view pages for a single URI based on auth status

查看:71
本文介绍了Laravel 4:基于身份验证状态的单个URI的两个不同视图页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用Laravel 4进行开发,我对路线有疑问.

I have recently got into developing with Laravel 4 and I had a question about routes.

对于'/',我想根据用户的身份验证状态使用两个不同的视图页面.

For '/', I would like to have two different view pages based on the user's auth status.

如果用户已登录并正在查看"/",我想向他们显示带有管理控件的视图,并且当用户以常规用户身份在未登录的情况下以"/"查看时,我想提供一个常规信息视图.

If a user is logged in and is viewing '/', I would like to show them a view with admin controls and when a user is viewing '/' as a regular user without logging in, I would like to offer a general information view.

为此,我一直在使用过滤器"auth"和"guest",但没有运气. //app/routes.php

To accomplish this, I've been playing around with filter 'auth' and 'guest' but am having no luck. // app/routes.php

// route for logged in users
Route::get('/', array('before' => 'auth', function()
{
   return 'logged in!';
}));

// for normal users without auth
Route::get('/', function() 
{ 
    return 'not logged in!'; 
}));

上面的代码工作到这样的程度:作为登录用户,我能够显示正确的响应,但是注销后,我不能以普通用户的身份看到正确的响应.

The above code works to a point where the as a logged in user, I am able to display the proper response but after logging out, I cannot see the proper response as a regular user.

也许这应该在控制器中处理?如果有人可以指出正确的方向,那将真的很有帮助.

Perhaps this is something that should be handled in the controller? If someone could point me in the right direction, it would be really helpful.

推荐答案

一个(简单的)选项是使用 Auth::check() 函数,以查看它们是否已登录:

One (simple) option would be to use the Auth::check() function to see if they are logged in:

Route::get('/', function() 
{
    if (Auth::check())
    {
        return 'logged in!';
    }
    else
    {
        return 'not logged in!'; 
    }  
});

如果愿意,您将能够在控制器中使用相同的逻辑.

You would be able to use the same logic in the controller if you so wish.

编辑-使用过滤器

如果您想在过滤器中执行此操作,则可以使用以下内容:

If you wanted to do this in the filter, you could use something like this:

Route::filter('auth', function()
{
    if (Auth::guest()) 
    {
        return Redirect::to('non-admin-home');
    }
});

,然后定义第二条路由(或控制器中的操作)来处理普通用户.

and then defining a second route (or action in your controller) to handle the normal users. Though this would mean a different url for the page, which I don't think is what you want..

基于控制器的完整布线流程:(保持routes.php清洁)

routes.php

Route::controller('/', 'IndexController');

IndexController.php

class IndexController extends BaseController
{
    // HOME PAGE
    public function getIndex()
    {
        if (Auth::check())
        {
            return View::make('admin.home');
        }
        else
        {
            return View::make('user.home');
        }
    }
}

这篇关于Laravel 4:基于身份验证状态的单个URI的两个不同视图页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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