Framework: Eager loading won't work when `firstOrCreate()`

Created on 15 Apr 2018  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.6
  • PHP Version: 7.2
  • Database Driver & Version: mysql

Description:

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();

Most helpful comment

You can use load():

$comment = Comment::firstOrCreate(...)->load('user');

All 3 comments

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.

Was this page helpful?
0 / 5 - 0 ratings