Home > Back-end >  Laravel 8 define belongsToMany definition in Model factory
Laravel 8 define belongsToMany definition in Model factory

Time:10-07

I'm trying to create a Request factory that will assign multiple random users for every individual Request instance that is created using said factory.

using the method definition in the Factory I am able to assign a belongsTo for Media, but it's not clear to me how I can create a belongsToMany for users.

This is my Request model:

class Request extends Model
{
    use HasFactory;

    public function media()
    {
        return $this->belongsTo('App\Media');
    }

    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

This is the Factory that I have right now:

class RequestFactory extends Factory
{

    protected $model = Request::class;

    public function definition()
    {
        return [
            // This is the belongsToMany relationship (that doesn't work) defined as users() in the Request model.
            'users' => function() {
                return User::inRandomOrder()->random(random_int(1,5))->get()->pluck('id');
            },
            // This is the belongsTo relationship (that works)
            'media_id' => function() {
                return Media::inRandomOrder()->first()->id;
            }
        ];
    }
}

Aside of the key users I also tried user_id & User::class hoping that Laravel would pick up on the array, and automatically use it in the relationship, but unfortunately that didn't work either since that column doesn't exist.

How can I make this work specifically from within the factory?

CodePudding user response:

i think when you do a belongToMany Relation, there is another table between Request and User which can be called UserRequest, You cant specified it in a Factory like this, but you can create a after create function to create the link between the users and the request in the third table You can see it here on documentation. https://laravel.com/docs/8.x/database-testing#factory-callbacks

You can add this following method in your factory class:

public function configure()
{
    return $this->afterMaking(function (Request $request) {
        //
    })->afterCreating(function (Request $request) {
        //
    });
}
  • Related