Chriz74
Chriz74

Reputation: 1480

how do I access or retrieve the key value of an associative array in laravel / eloquent?

I used the query builder to select an item from my DB, now if I do DD ($item) I get an associative array like:

array:1 [
  0 => {
    "id": 1,
    "itm_id": 615,
    "itm_val_id": 5,
    "created_at": "2015-10-26 09:42:23",
    "updated_at": "2015-10-26 09:42:23"
  }
]

I need to attach the ID to the user in a pivot table, the question is: how do I get that id??

Upvotes: 1

Views: 201

Answers (2)

Peter Kota
Peter Kota

Reputation: 8350

You can use attach like this:

Auth::user()->item()->attach($item[0]->id);

Auth::user()->item()->attach([1 => ['itm_id' => $item[0]->id], $item[0]->id]);

You can read more about many to many relation in Laravel docs.

Upvotes: 0

Chriz74
Chriz74

Reputation: 1480

that doesn't work, but this works:

Auth::user()->item()->attach($item[0]->id);

Upvotes: 1

Related Questions