L
L
lynnikvadim2015-09-13 19:57:50
Laravel
lynnikvadim, 2015-09-13 19:57:50

Laravel model error?

Why it doesn't work:
$org = OrgModel::all()->user();
But it works: $org = OrgModel::find($id)->user();
Both lines are in the same controller in different functions.
This code is for the relationship of two tables. ( ->user(); )
Writes an error:

Call to undefined method Illuminate\Database\Eloquent\Collection::user()

What am I doing wrong ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Brezhnev, 2015-09-13
@vanchelo

Because the all method returns a collection of models, not a single model.

$org = OrgModel::all();
foreach ($org as $item) {
    $item->user();
}

But it's not right to do it this way, it's right like this
$org = OrgModel::with('user')->all();
foreach ($org as $item) {
    var_dump($item->user);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question