1
1
1programmer2018-04-23 13:50:03
Laravel
1programmer, 2018-04-23 13:50:03

Why is it not displaying data in the foreach loop?

There is a table Items it has id, name, description

$itemRandom = Item::inRandomOrder()
                        ->limit(1)
                        ->get();

                    $item = $itemRandom[0];

I get a random element from the base in this way, then I pass it to the view Into the view if I output it like this
return view('my-form')->with('item',$item);
< p >{{ $item }}< /p >
, then I get this
{"ID":9,"NAME":"2FGDSDGDSF","DESCRIPTION":"E1E21E12EASADASF","CREATED_AT":"2018-04-22 17:53:48","UPDATED_AT":"2018-04-22 17:53:48"}

I need to get only name and description
Tried to output like this
@foreach($item as $items)
        <p>
            Вашь приз: {{ $items->name }}</br>
            Описание:
        </p>
        @endforeach

Got this:
"Trying to get property 'name' of non-object

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav Nagorny, 2018-04-23
@1programmer

$item = Item::inRandomOrder()->first();
return view('my-form',compact('item'));

Y
Yan-s, 2018-04-23
@Yan-s

After all, you only have 1 item after you do $itemRandom[0]
That is, no loop is needed, just

<p>
    Вашь приз: {{ $item->name }}</br>
    Описание:
</p>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question