Reputation: 5233
I'm trying to get data from an Eloquent query as follows:
$submission->find($id)->first()->with('user', 'clientform')->get();
I'm sending the submission to the view and attempting to access properties from the user
model like so:
{{ $submission->clientform->name }}
However, Laravel is throwing the following error:
Undefined property: Illuminate\Database\Eloquent\Collection::$clientform
What am I doing wrong with the way my query is formatted?
Upvotes: 1
Views: 667
Reputation: 4117
You're overdoing it!
Let's break it down:
$submission->find($id);
Will return an instance of the model which corresponds to the entry having the primary key of $id
.
$submission->find($id)->first();
This is an unncessary repetition; the find
method already gives you a single entry, no need to call first
on it.
$submission->find($id)->first()->with('user', 'clientform');
This is where you start going the wrong way; when calling with on a model, Laravel will transform that model into a query builder again, even though it was already resolved by calling find
.
$submission->find($id)->first()->with('user', 'clientform')->get();
Finally, the get
method resolves the builder into a Illuminate\Support\Collection
, regardless of the number of entries found (i.e. it could be a Collection
of only one item). It's worth noting, though, that your query will most likely have been fully reset by calling with. It would be the same as instantiating a fresh Submission
model and building your query with it. That means you're probably using a collection of all your submission entries, not just the one with $id
.
Long story short, this is what you want:
$submission->with('user', 'clientform')->find($id);
It will fetch the matching $id
, with the user
and clientform
relations eager-loaded.
Upvotes: 2