Miura-shi
Miura-shi

Reputation: 4519

Eloquent Return Non Associative Array?

I am trying to get an array list of IDs to pass onto another model query.

$companies = $user->companies->pluck('id');

But it keeps returning an associative array as such:

[ 0 => 2, 1 => 9]

So when I pass it to the find method on my Company model, like this

$company = Company::find($companies);

I get the following error:

Trying to get property of non-object

I need to be able to pass a non-associative array to the call like such:

Company::find([2,9]);

Upvotes: 1

Views: 2477

Answers (3)

Paul Spiegel
Paul Spiegel

Reputation: 31832

As you can see in Laravels source code

src/Illuminate/Database/Eloquent/Builder.php

public function find($id, $columns = ['*'])
{
    if (is_array($id)) {
        return $this->findMany($id, $columns);
    }
    $this->query->where($this->model->getQualifiedKeyName(), '=', $id);
    return $this->first($columns);
}

find() will internally call findMany() if the first parameter is an array. But $user->companies->pluck('id') returns a Collection and the Builder creates a wrong query. So your options are:

Use findMany():

$company = Company::findMany($companies);

Convert the Collection to an array:

$company = Company::find($companies->toArray());

Use whereIn():

$company = Company::whereIn('id', $companies)->get();

But actually that all doesn't seem to make any sense, because $user->companies probably already contains the collection you want to fetch from DB. So you could also write:

$company = $user->companies;

However - the fact that you are using singular naming (company) for a set of companies, let me think that you are trying to achieve something completely different.

Upvotes: 1

Rocco Milluzzo
Rocco Milluzzo

Reputation: 1007

Try that:

$companies = $user->companies->pluck('id')->toArray();

Just did a test in tinker and the result is a flat array, the "find" will work for sure!

Upvotes: 3

Sylwit
Sylwit

Reputation: 1577

You can try with the whereIn method

Company::whereIn('id', $companies)->get();

Upvotes: 0

Related Questions