For example if I have a comment model like this
class Comment extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
The following code won't get me a user model in the first place, I have to fetch it myself.
$comment = Comment::with('user')->firstOrCreate([
'user_id' => Auth::id(),
'post_id' => $request->get('post_id'),
'content' => $request->get('content')
]);
// `user` property not exists,
// I have to fetch the `user` manually by calling `$comment->user`.
$comment->toJson();
You can use load():
$comment = Comment::firstOrCreate(...)->load('user');
Can you please close the issue?
Or if you are like me, and using protected $with = [...] in models, for automatically eager loading multiple relationships, you could use fresh()
$comment = Comment::firstOrCreate(...)->fresh()
This will... refresh your model and load all relationships.
Anyway, not a real issue but I would consider this an inconsistency of Laravel Framework.
Most helpful comment
You can use
load():