code-8
code-8

Reputation: 58662

Pass data from controller to view laravel 5

Controller

public function codingPuzzleProcess()
{

    $word     = Input::get('word');
    $length   = strlen($word);


    return Redirect::to('/coding-puzzle')
        ->with('word', $word )
        ->with('length', $length )
        ->with('success','Your word was submit succesfully!');

}

View

I tried to access those data in my blade view like this

{!!$word or '' !!} | {!!$length or '' !!}

and I'm not sure why I got nothing printing. I'm sure that my

$word = 'love' with length of 4

Any hints / suggestion on this will be much appreciated !

Upvotes: 1

Views: 2114

Answers (3)

Jeff Lambert
Jeff Lambert

Reputation: 24661

A redirect doesn't pass control to a view, it passes control to the client, which then issues another, separate request, to the application.

This request will then be handled by a controller which can send data to a view like I think you are trying to. However, when you redirect and pass data like this, the data will not just become magically available in the current scope. It will instead be magically available in the session flash data:

{!! $word = session('word') ? $word : '' !!}

Manual

Upvotes: 3

Javi Stolz
Javi Stolz

Reputation: 4755

You got confused between the with() method of the redirect response and the with() method of the view class. Although similar they don't do the same. The first one, defined in Illuminate\Http\RedirectResponse flashes the values to the session. The second one, defined at Illuminate\View\View, passes the values to the view.

Since you are returning a Redirect response, you values will not be directly accessible as variables in your view. You will need to use the session() or old() helper to access those values from your views.

Upvotes: 1

JuanDMeGon
JuanDMeGon

Reputation: 1211

First at all, you don't need to redirect, you can use a return view statement and send the data, like this:

return view('coding-puzzle', ['word' => $word, 'lenght' => $lenght, 'success' => 'Your word was submit succesfully!']);

Then in your view you can just access these variables in the way that you want: {{$word}} ("scaping" the variable value or {!!$word!!} to do not scape it.

Now, iy you really need to do a redirection, so you can't access these variables in the "normal" way, you need to access it through the session, like this:

@if(Session::has('word'))
    {{Session::get('word')}}
@endif

And in the same way with the others.

Hope it helps.

Let me invite you to a Laravel Step-by-Step course to get more deeper knowledge:Learn Laravel Step By Step

Best wishes.

Upvotes: 1

Related Questions