Streetlamp
Streetlamp

Reputation: 1556

Pass an object to a view from controller

I am trying to pass a set of rows from a controller to a view:

$items = Items::where('group', '=', $group);
return view('listing', [
    "group" => $group,
    "exists" => $items->exists(),
    "items" => $items->get(),
]);

And in my view:

@if (!$exists)
    Nothing
@else
<ul id="items">
@foreach ($items as $item)
    <li>
        {{ $item->user }}: {{ $item->content }}
    </li>
@endforeach
</ul>
@endif

The view will only return 1 item though. The length of $items is 1. If I count($items) in the controller, I get the expected number of items.

How can I pass an object to my view from a controller?


My final solution:

Controller

$items = Items::where('group', '=', $group);
return view('listing', [
    "group" => $group,
    "items" => $items->get(),
    "exists" => $items->exists(), // Important! Has to go after!
]);

And in my view:

@if (!$exists)
    Nothing
@else
<ul id="items">
@foreach ($items as $item)
    <li>
        {{ $item->user }}: {{ $item->content }}
    </li>
@endforeach
</ul>
@endif

Upvotes: 2

Views: 85

Answers (2)

patricus
patricus

Reputation: 62278

The issue is the call to exists() before the call to get(). The call to exists() is modifying your query builder to add a limit(1) to it. Therefore, when you call get() after exists(), the query builder still has the limit(1) attached.

Your updated solution works because you removed the call to exists().

However, the call to get() should still be done in the Controller. The view should only be passed the collection of objects, not the query builder.

Upvotes: 2

whoacowboy
whoacowboy

Reputation: 7447

I believe if you put get() at the end it will work.

$items = Items::where('group', '=', $group)->get();

You are just pulling back the model object and not the data. That is why the count is 1 when you are expecting 4.

Edited per comment

I think the get where you have it might be causing some funkiness.

$items = Items::where('group', '=', $group)->get();
return view('listing', [
    "group" => $group,
    "items" => $items,
]);


@if (!$items->exists())
    Nothing
@else
<ul id="items">
@foreach ($items as $item)
    <li>
        {{ $item->user }}: {{ $item->content }}
    </li>
@endforeach
</ul>
@endif

You might put a dd($items->toArray()); after you query Items to see what you get.

Upvotes: 0

Related Questions