Courses

Filament 3 From Scratch: Practical Course

BelongsToMany: Multi-Select and Relation Managers

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Setting up many-to-many relationships
- Using select multiple field
- Implementing relation managers
- Managing attach/detach functionality in the relation managers

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

Text Version of the Lesson

Now, let's see how we can add data to a many-to-many relationship. Let's say that our Product may have many Tags.

We generate the Model+Migration:

php artisan make:model Tag -m

Here's the structure, with relationship right away:

Migration

Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});

app/Models/Tag.php:

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class Tag extends Model
{
protected $fillable = ['name'];
 
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class);
}
}

Also, the relationship from the other way:

app/Models/Product.php:

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class Product extends Model
{
// ...
 
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
}

Next, we generate this simple Filament Resource:

php artisan make:filament-resource Tag --simple --generate

The result is this:

But, of course, the Tags CRUD is not the topic of this lesson. What we need to do is add tags to products. Multiple tags.

There are a few ways to do it.


Option 1. Just Attach: Select Multiple

Let's add one more field in the form of...

The full lesson is only for Premium Members.
Want to access all 24 video+text lessons of this course? (2 h 01 min)

You also get:

  • 79 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord