Brad Ahrens
Brad Ahrens

Reputation: 5168

Laravel - Unable to variable from controller to view

I'm creating a site in Laravel that uses a controller to validate the information from a form and then return the user to a Thanks page. On that thanks page, I would like to use the user's name and gender.

In my controller I have:

return redirect()->route('thanks')->with(['success' => 'success', 'name' => $name, 'gender' => $gender]);

Then, in the view, I have:

<p>{{ $name }}</p>
<p>{{ $gender }}</p>

But, for some reason I keep getting this error:

Undefined Variable: Name

What's weird is that if I die and dump $name within the controller, it shows it properly on the screen.

I've tried various different ways to try to pass multiple variables through to the view as well as different variable names and forms to receive it again... but haven't been able to make it work.

Do you guys have any idea where I could be going wrong? As, always, I really appreciate your help! All ideas, suggestions, and comments are welcome :) Thanks!!

Upvotes: 0

Views: 163

Answers (2)

Sunil kumawat
Sunil kumawat

Reputation: 804

If you redirect to URL with data then you can get the data form session.

return redirect()->route('thanks')->with(['success' => 'success', 'name' => $name, 'gender' => $gender]);

write in your view

{{ Session::get('name') }}

{{ Session::get('gender) }}

And if you redirect direct to the view like this

return view('thanks')->with(['success' => 'success', 'name' => $name, 'gender' => $gender]);

then write in your view

<p>{{ $name }}</p>
<p>{{ $gender }}</p>

Upvotes: 2

Devon Bessemer
Devon Bessemer

Reputation: 35337

with() on a redirect flashes data to the session, it does not involve anything with views. You shouldn't confuse this method call with views and redirects as they are not equivalent.

The only place where variables are passed to the view is where you're returning the view:

return view('thanks')->with(['success' => 'success', 'name' => $name, 'gender' => $gender]);

Since you're using a redirect, you would need to pull this data from the session to pass into the view (or access the data from the session directly in the view).

Or you could just return this view from your controller instead of redirecting in the first place.

Upvotes: 3

Related Questions