Pedram marandi
Pedram marandi

Reputation: 1614

undefined offset 0 with eloquent collection

When i try to make query like this :

$result = Entity::with (
    [ 'councils' => function ($query) use ($userId) {
        $query->active()->with([
        'members' => function ($query) use ($userId) {
            $query->where ('user', $userId);
        }
        ])->first();
    }])->find ($entityId);

but eloquent return relations into an array. i need to use something like this :

$result->councils[0]->members[0]->pivot->role;

how can i get collection without array offsets and use above result like this one :

$result->councils->members->pivot->role;

my dd() from $result variable :

 #attributes: array:15 [▶]
  #original: array:15 [▶]
  #relations: array:1 [▼
    "councils" => Collection {#362 ▼
      #items: array:1 [▼
        0 => Council {#360 ▼
          #guarded: array:1 [▶]
          #connection: null
          #table: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:14 [▶]
          #original: array:14 [▶]
          #relations: array:1 [▼
            "members" => Collection {#364 ▼
              #items: array:1 [▼
                0 => User {#359 ▶}
              ]
            }
          ]
          #hidden: []
          #visible: []
          #appends: []
          #fillable: []
          #dates: []
          #dateFormat: null
          #casts: []
          #touches: []
          #observables: []
          #with: []
          #morphClass: null
          +exists: true
          +wasRecentlyCreated: false
        }
      ]
    }
  ]

Upvotes: 1

Views: 803

Answers (1)

Javi Stolz
Javi Stolz

Reputation: 4755

To get the first element of a collection use ->first()

$result->councils->first()->members->first()->pivot->role;

To get an element by its key use ->find($key)

$result->councils->find(0)->members->find(0)->pivot->role;

It's a good practice to check first if the element exists with the method ->contains($key)

if($result->councils->contains(0)) ...

more info here http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Collection.html

Upvotes: 1

Related Questions