How to pass data through a redirect to a view in laravel

ε祈祈猫儿з 提交于 2019-12-06 14:53:45

...

Update

Storing $user_id on a hidden input is a bit risky, how if your user know how to change the value on browser such as Chrome developer console and replace it with another user id?

Rather than storing it on hidden input I would store it as session flash data, it could be:

public function confirm($confirmationCode){
    ....

    session()->flash('user_id', $user_id); // Store it as flash data.

    return redirect('assign-username');
}

On AuthenticationController@showAssignUsernameForm tell Laravel to keep your user_id for next request:

public function showAssignUsernameForm() {
    session()->keep(['user_id']);
    // or
    // session()->reflash();

    return view('your-view-template');
}

And on your assign username POST method you can define the value like this:

public function assignUsername(){
    $user_id  = session()->get('user_id');
    $username = request()->input('username');

    if(User::where('username', '=', $username)->exists()) {
        session()->flash('user_id', $user_id); // Store it again.

        return redirect()->back()->withInput()->withErrors([
            'username' => 'Este usuario ya se encuentra registrado. Intenta nuevamente'
        ]);
    } else {
        DB::table('user')->where('user_id', $user_id)->update(['username' => $username]);
    }
}

This should work:

public function assignUsername(Request $request)
{
    $user_id = $request->user_id;

If you're passing data to the view, to get the information after with(compact('user_id')) you must do through Session like this:

 @if (session('user_id'))
    <input type="hidden" name="user_id" value="{{ session('user_id') }}">           
@endif
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!