Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()->count(2)->create();

$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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading