How to pass several variables to a View in Laravel?

Asked

Viewed 610 times

0

How do I pass several variables to the same view? Something like:

return "view('textos.index', ['textos1' => $textos1, 'textos2' => $textos2, 'textos3' => $textos3]);"
  • The right thing wouldn’t be return view('textos.index', ['textos1' => $textos1, 'textos2' => $textos2, 'textos3' => $textos3]);?

2 answers

3

That’s exactly how it is:

return view('textos.index', [
                 'texto1' => $texto1,
                 'texto2' => $texto2, 
                 'texto3' => $texto3
             ]);

And in the view you access it this way:

<div>
    <p>{{$texto1}}</p>
    <p>{{$texto2}}</p>
    <p>{{$texto3}}</p>
</div>

The only thing wrong there is that you put it in quotes, so Voce was returning a String

2

In your case, you can also use the function compact.

This function captures the names of the local variables and creates an associative array with the appropriate values.

So it could be done like this:

$texto1 = 1;
$texto2 = 2;
$text3 = 3;

return view('home', compact('texto1', 'texto2', 'texto3'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.