Andrés Buitrago Andrés Buitrago - 6 months ago 48
PHP Question

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

How can I pass data from a controller after it performs certain action to a view through a

redirect()
if I have a get route for it?

The logic of the app is to redirect with an
user_id
to a view where the user will select its username after successfully verified its email.

public function confirm($confirmationCode){
if(!$confirmationCode){
dd('No se encontró ningún código de verificación en la URL');
}
$user = User::where('confirmation_code', $confirmationCode)->first();
if(!$user){
dd('Lo sentimos. Este código de confirmación ya ha sido usado.');
}
$user->confirmed = 1;
$user->confirmation_code = null;
$user_id = $user->user_id;
$user->save();

return redirect('assign-username')->with(compact('user_id'));
}


The get route:

Route::get('assign-username', 'AuthenticationController@showAssignUsernameForm');


And the code for the post request of the
assign-user
form.

public function assignUsername(){
$user_id = request()->input('user_id');
$username = request()->input('username');
if(User::where('username', '=', $username)->exists()){
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]);
}
}


When trying to access to the
$user_id
variable it says it is not defined.

The view's code:

@extends('layouts.master')
@section('content')
<section class="hero">
<h1><span>Ya estás casi listo.</span>Es hora de seleccionar tu nombre de usuario</h1>
<div class="form-group">
<form class="form-group" method="post" action="assign-username">
{!! csrf_field() !!}
@if($errors->has('username'))
<span class="help-block" style="color:red">
<strong>{{ $errors->first('username') }}</strong>
</span>
@endif
<input type="hidden" name="user_id" value="{{ session('user_id') }}">
<input type="text" name="username" placeholder="Escribe tu nombre de usuario">
<button type="submit" class="btn" name="send">Registrar</button>
</form>
</div>
</section>
@endsection


Laravel Version: 5.2

Answer

...

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]);
    }
}