Laravel-如何在返回重定向中使用变量


Laravel - How to use variable in view from a return Redirect?

我是Laravel的新手,正在尝试使用它的功能。 但是,我坚持能够使用$username变量

在我的UserController课上,我有以下方法:

public function handleRegister()
{
    $user = new User();
    $user->email = Input::get('email');
    $user->username = Input::get('username');
    $user->password = Hash::make(Input::get('password'));
    $user->save();
    return Redirect::to('login')->withInput(array('username', $user->username));
}

我的这部分代码运行良好,因为当我var_dump(Input::Old())使用"Jon"作为用户名时,/login 会返回以下内容:

array(2) { [0]=> string(8) "username" [1]=> string(3) "Jon" }

对于/login 的用户名输入字段,我尝试使用以下方法使用该值:

value="{{ Input::old('username') or '' }}"

但是,输入字段的值始终为 ''。

我做错了什么?

更新:

将返回值追逐到以下内容后:

return Redirect::to('login')->withInput(Input::only('username'));

并尝试检索值:

value="{{ Input::old('username') }}

用户名字段的值设置为 1,而不是"Jon"。

我不知道为什么。

您正在使用魔术函数"with"发送变量"input",并且您正在影响此变量的数组,因此在刀片模板中,您可以使用以下代码访问它:

// If you want to keep the recent post inputs, use withInput without parameters
return Redirect::to('login')->withInput();
// and then use this code to echo it
 {{ Input::old('username') }}

但我想如果你使用 Laravel's From 和这样的模型绑定会更好:

{{ Form::model($user, array('route' => array('user.update', $user->id)))
    {{ Form::label('username', 'Username : ') }}
    {{ Form::text('username') }}
{{ Form::close() }}

在这里,用户将被绑定到路由中带有 id 的对象,例如:users/1 Laravel将获取 id 为 1 的用户并将其绑定到您的表单。但是如果我们谈论的是身份验证或创建,则不需要模型绑定,只需使用laravel的形式:

{{ Form::open(array('route' => array('yourRouteName')))
    {{ Form::label('username', 'Username : ') }}
    {{ Form::text('username') }}
{{ Form::close() }}

请注意,您可以在路由中使用模型绑定,因此当您可以直接在控制器中访问对象时,例如,我想编辑和反对,并且按照 RESTFul 架构,我将有以下路由:

Route::put('users/{id}', array('as' => 'users.update', 'uses' => 'UserController@update'));

然后在控制器中,我将尝试检索在 URL 中传递 id 的用户,但是在使用模型绑定时,我将在我的控制器中获取一个 user 对象,您可以这样做,首先通过更改路由:

// we create a model binding
Route::model('user', 'User');
// and we use it in our route instead of the id
Route::put('users/{user}', array('as' => 'users.update', 'uses' => 'UserController@update'));

现在在我们的控制器中,我们可以接受一个用户,并对该对象做任何我们想做的事情:

public function update($user)
{
    var_dump($user);
}

现在,当您有类似 : users/4 获取 ID 为 4 的用户时,会自动完成。