laravel 4通过1d显示查询用户


laravel 4 display query user by 1d

我正在为一个web项目使用Laravel 4,我正在创建一个管理面板

在管理员中,我有admin/profile/{id}来显示用户配置文件,如名字、姓氏等。

在我的AdminController中,我有:

     // get the Admin Profile page
    public function getProfile($id) {
    // get the user from the database
    $user = User::find($id);
    $this->layout->content = View::make('admin.profile', array('user' => $user));
    }

但是如果我只是在没有任何用户id的情况下转到admin/profile,会发生什么,我该如何让它工作?

基本上,如果页面不存在,如何转到仪表板或类似的东西?例如,如果他们尝试了admin/test,而test不是一种方法,如果他们登录了,它将转到仪表板,如果没有,它将进入登录页面?

您要问两个问题:

  1. 如果我在没有用户ID的情况下转到admin/profile,我会收到404错误。如何重定向到登录页面?

  2. 如果用户没有登录,我如何重定向到登录页面。

对于第一个问题,你可以用几种方法来回答。一种解决方案是在所有其他路由定义:之后添加一条匹配任何的路由

Route::get('{any_url}', function(){ return Redirect::route("login"); });

必须是最后定义的路由,因为它将匹配任何URL。

另一种方法是在start/global.php文件中捕获NotFoundHttpException。添加此代码:

App::error(function('Symfony'Component'HttpKernel'Exception'NotFoundHttpException $exception, $code)
{
    return Redirect::route("login");
});

这两个示例都重定向到一个名为login的命名路由。

至于第二个问题,正确的处理方法是使用auth过滤器。在filters.php文件中,您可以添加以下内容:

Route::filter('auth', function($route)
{
    // is the user authorized? if not, redirect to the login page
    if (!user_is_authorized())
    {
            // redirect to the login page
            return Redirect::route('login');
    }
});

其中user_is_authorized函数只是您在代码中进行的任何检查的简写。有关使用auth筛选器的信息,请参阅http://laravel.com/docs/routing#route-过滤器。

您可以简单地添加一个missing处理程序(处理404),如下所示:

App::missing(function($e){
    // Log the missing url
    Log::error($e);
    // You may redirect to home
    return Redirect::to('/');
    // Or redirect to a 404 route that is declared
    // to show a custom 404 page from that route
    return Redirect::to('missing');
});

将代码(上面给出的)放在app/start/global.php文件中。对于missing url/route,您需要在routes.php文件中添加一条路径,如下所示:

Route::get('missing', function(){
    // show the view: errors.missing
    $this->layout->content = View::make('errors.missing');
});

view创建为views/errors/missing.blade.php,并在missing.blade.php视图中显示一条奇特的消息,通知访问者requested page/url不可用,并在该404页面中添加指向主页的链接。

Laravel网站上阅读更多关于Errors&日志记录,检查处理404错误。