Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daghsny's avatar

How To create Factories for manyTaMany Relationship?

i have two tables field and level

class Field extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'description',
    ];
    public function levels(): BelongsToMany
    {
        return $this->belongsToMany(Level::class, 'fields_levels');


    }
    
}
class Level extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
    ];
    public function fields(): BelongsToMany
    {
        return $this->belongsToMany(Field::class, 'fields_levels');
    }

    }

Migration

NB: i Have just 3 level ['1st Level', '2nd level,'3rd level'] and 4 Fields ['English' , 'French' , 'Math', 'Computer science']

0 likes
3 replies
jj15's avatar

@Daghsny Can you please share the error you're receiving, the code for the factories, and the code where you're calling the factory?

Please or to participate in this conversation.