【问题标题】:Force URL Parameter if none given in Laravel 4如果 Laravel 4 中没有给出,则强制 URL 参数
【发布时间】:2014-06-20 02:14:51
【问题描述】:

我有一个网址:http://localhost/laravel/projectx/public/user/username

目前它读取username 以输出某些结果,例如它是谁的页面,这很好,但如果他们只输入http://localhost/laravel/projectx/public/user,它会重定向到localhost/user,但我需要它来呈现配置文件用户页面是他们自己的(返回到http://localhost/laravel/projectx/public/user/me URL)。知道我该怎么做吗?

我的路线如下,但是不行?

Route::get('/user/', array(
'as' => 'profile',
'uses' => 'ProfileController@user'
));

Route::get('/user/{username}', array(
'as' => 'profile-user',
'uses' => 'ProfileController@user'
));

以及 ProfileController 控制器中的代码:

public function user($username = null) {

    if($username != null) {
        $user = User::where('username', '=', $username);
        if($user->count()) {
            $user = $user->first();
            return View::make('profile.user')->with('name', $user->username);
        }
    }
    return View::make('profile')->with('name', Auth::user()->username);

}

【问题讨论】:

  • Route::get('user/{username?}', ...

标签: php routing laravel-4 query-string


【解决方案1】:

您只能使用一条路线:

Route::get('/user/{username?}', array(
    'as' => 'profile-user',
    'uses' => 'ProfileController@user'
));

我会在你的控制器中使用这样的东西:

public function user($username = null) 
{
    $user = $username 
            ? User::where('username', '=', $username)->first() 
            : null;

    if ( ! $user && Auth::check())
    {
        $user = Auth::user();
    }
    else
    {
        return Redirect::to('/');
    }

    return View::make('profile')->with('name', $user);
}

【讨论】:

  • 不起作用,当没有指定用户时仍然重定向到localhost/user
  • 是的,我忘了添加?。已编辑。
猜你喜欢
  • 1970-01-01
  • 2013-07-11
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 2017-01-02
  • 2015-06-11
相关资源
最近更新 更多