将变量从路由传递到控制器

时间:2014-02-26 21:52:24

标签: php laravel

我在这里有一个大问题,我不知道如何解决它。

routes.php文件:

Route::group(array('prefix' => 'user'), function() {

    Route::post('/{user}/{char_name}/selectedok', array(
        'as' => 'char-profile-post',
        'uses' => 'ProfileController@postDropDownList'
    ));   

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

});

ProfileController.php:

public function getDropDownList() {  

    return View::make('layout.profile');     

}



public function postDropDownList($user, $char_name) {

    if (Auth::check())
    {   
        $user = Auth::user();
        $selected_char = Input::get('choose');
        $char_name = User::find($user->id)->characters()->where('char_name', '=', $selected_char)->first();


        return Redirect::route('char-profile-get', array($user->username, $char_name->char_dynasty, $char_name->char_name))
                ->with('user', $user->username)
                ->with('charname', $char_name->char_name)
                ->with('dynastyname', $char_name->char_dynasty);



    }
}

是的我知道我重定向到char-profile-get有3个参数,但我只需要2.它不会打扰我。如您所见,我使用->with重定向。我将在视图中打印数据的唯一方法是在视图中执行此操作:

您选择的角色是

{{ Session::get('charname') }} {{ Session::get('dynastyname')}}

如果我不覆盖postDropDownList($user, $char_name) URL中的变量,我的 http://localhost/CaughtMiddle/tutorial/public/index.php/user/%7Buser%7D/%7Bchar_name%7D/selectedok 字面意思如下:

 http://localhost/CaughtMiddle/tutorial/public/index.php/user/SerbanSpire/Spirescu/selectedok?Serban

而不是:

var_dump($user)

所以判决结果。函数中的参数永远不会收到任何数据。我甚至不知道如何描述它们,函数的参数为​​null,即使我使用正确的数据重定向到get路由。 var_dump($char_name)dd($user)未在浏览器上打印任何内容,dd($char_name)print_r()也不会打印任何内容,也不会->with

我的解决方案是否可行?通过使用Session::get()重定向并将数据存储在Session中?因为每次我使用数据库中的信息时,这个解决方案会让我经常使用{{1}},但我不会更新它!如果我错了,请阻止我。

为什么路径中的变量不是我的函数的参数?如果我的函数没有任何参数,代码将起作用。基本上,那些参数都没有。

3 个答案:

答案 0 :(得分:1)

我终于设法解决了我的问题。我创建了一个新的CharacterController.php文件,并将get函数放在新控制器中。这样,函数的参数将成功到达并有用。

答案 1 :(得分:0)

如果我理解正确你只需要

        return Redirect::route('char-profile-get', array(
        'username' => $user->username,
        'char_name' => $char_name->char_name))
        ->with('user', $user->username)
        ->with('charname', $char_name->char_name)
        ->with('dynastyname', $char_name->char_dynasty);

因为你传递一个空数组。 现在直接在视图中使用Session :: get('username')和Session :: get('char_name')(layout.profile)

答案 2 :(得分:0)

你可以试试这个

$user = Auth::user();
$char = $user->characters()->where('char_name', Input::get('choose'))->first();

return Redirect::route('char-profile-get')
               ->with('user', $user->username)
               ->with('charname', $char->char_name)
               ->with('dynastyname', $char->char_dynasty);
相关问题