There are many methods to pass data, especially data queried from the database.
This shot explains how to use the compact()
method to elegantly parse data to your views.
Go to the Controller
to implement the method.
When you have several variables with saved data and you want to parse to view
, you can use the compact()
method.
For example:
$users = User::all();
$posts = Post::all();
return view('/comment',compact('users','posts'));
In the code above, we return the comment
view
, which should typically be in your resources/views
directory as comment.blade.php
. We parse the data as a string, in the same fashion as it is written.
To get the data while in the comment
view, we use @foreach
to loop through the values like so:
@foreach($users as $user)
.
Then, end the foreach
statement after you are done: @endforeach
.
The compact()
method makes it a lot easier to parse data to the view in a readable format.