user14812075
user14812075

Reputation: 53

Property [id] does not exist on this collection instance - Laravel 6

I am trying to load data into a table using a foreach but I get the error

Property [id] does not exist on this collection instance.

What could I be doing wrong?

Response looks like this:

{
   "id": 1,
   "name": "Apple",
   "messages": [
      {
         "id": 7,
         "received": 0
      }
   ]
}   

Controller

public function show()
{
    $items = Item::with('messages')->where('user_id', Auth::user()->id)->get();
    return view('home', compact('items'));
}

View

@foreach($details as $detail)
    <td>{{ $details->messages->id }}</td>
@endforeach

Upvotes: 0

Views: 1405

Answers (2)

user10697540
user10697540

Reputation:

try this $userId = Auth::id(); and then where('user_id', $userId)->get()

Upvotes: 0

shn
shn

Reputation: 875

Looks like the join that you are doing on the Item table with the Messages table returns a list in the messages field. Shown here:

{"id":1,"name":"Apple""messages":[{"id":7,"received":0}]}  

Notice the [{"id":7,"received":0}].

To get the individual ID of a message, you would first need to index into the messages list. Or you could change the query to only select one message from each item.

Upvotes: 2

Related Questions