Level 10
Assuming you have created factories for the Field and Level models, you may use the has() method to create a many-to-many relationship as described in the documentation.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('fields_levels', function (Blueprint $table) {
$table->unsignedBigInteger('field_id');
$table->foreign('field_id')
->references('id')
->on('fields')
->onDelete('cascade');
$table->unsignedBigInteger('level_id');
$table->foreign('level_id')
->references('id')
->on('levels')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('fields_levels');
}
};
NB: i Have just 3 level ['1st Level', '2nd level,'3rd level'] and 4 Fields ['English' , 'French' , 'Math', 'Computer science']
Please or to participate in this conversation.