webfuelcode's avatar

How to use @foreach on index page

Good practice of using @foreach on the homepage.

I am trying to design two pages with different styles with posts loop from the database. One page is inside the member's area which is linked in the dashboard, so members can see it. Also, non-members can visit it if they have the link.

But I want to show the same list with a different style on the homepage. So how to use the @foreach and pass the value for the variable?

Basically, the question is about passing error. "Undefined variable:"

0 likes
4 replies
tykus's avatar

It might help to share some of your code

webfuelcode's avatar

Thanks, I got it.

Actually I was not clear about transferring the variable value on the homepage where you are not sending value through a link.

I knew it can be done using a controller but again it will have to make a link and transfer it.

Finally, I got this to make it happen. A small function on the route file.

Route::get('/', function () {
    $links = App\Link::paginate(8);
    return view('welcome', compact('links'));
});

And then I can use the @foreach loop on the homepage.

The error was "Undefined variable" for that particular variable I have used in foreach.

MichalOravec's avatar
Level 75

You can use partial view for that for example

@include('partials.list-of-posts', ['posts' => $posts, 'class' => 'your-class'])

where you pass $posts variable and inside that view you have foreach

@foreach ($posts as $post)
    //
@endforeach

So you just include it to your homepage and dashboard page.

Docs: https://laravel.com/docs/7.x/blade#including-subviews

Snapey's avatar

two routes, two controllers, the same model query in each.

Common views can be shared as partials.

Try and avoid using closures - at least up until Laravel 8 - they prevent route file caching.

Please or to participate in this conversation.