laravelfactorieslaravel-factory

How to get data of BelongsToMany relationship from Laravel factories make() method


I have a factory class which instantiate a Post Model without persisting the data to database/ without using create() method

$record = Post::factory()
    ->has(Comment::factory()->count(2))
    ->make([
        'title' => fake()->word,
        'user_id' => $user->id,
    ]);

From above implementation I got Post record.

I can access $record->user->name which is BelongsTo relationship. But I cannot access $record->comments which is BelongsToMany relationship, it returns empty collection

For my case, I do not want to persist the data to database.


Solution

  • In Laravel, while using model factories to create model instances, relationships are not automatically loaded when using the make() method. The make() method creates an instance of the model without persisting it to the database but doesn't automatically load its relationships.

    The relationships are not loaded by default with model instance created via make.You'll need to manually load the relationships after creating the model instance.

    $comments = Comment::factory()->create(2);
    
    $record = Post::factory()
        ->make([
            'title' => fake()->title,
            'user_id' => $user->id,
        ]);
    
    // Set the 'comments' relationship on the 'Post' model instance
    $record->setRelation('comments', $comments);
    
    //  access the comments
    dd($record->comments);
    

    The setRelation() method is used to manually set a relationship on the model instance. In this case, it helps to set the 'comments' relationship on the Post model instance after it has been created using the factory.