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.
For Tags, I've created a simple Model with one field, seeded a few tags, and then generated this simple Filament Resource:
php artisan make:filament-resource Tag --simple --generate
The result is this:
But, of course, it's not the topic of this lesson. What we need to do is add tags to products. Multiple tags.
The relationship in Eloquent is this:
app/Models/Product.php:
use Illuminate\Database\Eloquent\Relations\BelongsToMany; class Product extends Model{ // ... public function tags(): BelongsToMany { return $this->belongsToMany(Tag::class); }}
There are a few ways to do it.
Option 1. Just Attach: Select Multiple
Let's add one more field in the form of ProductResource
.
app/Filament/Resources/ProductResource.php:
return $form ->schema([ // ... Forms\Components\Select::make('category_id') ->relationship('category', 'name'), Forms\Components\Select::make('tags') ->relationship('tags', 'name') ->multiple(), ]);
Yes, that's it, all you need to do is add ->multiple()
to the Select field, and it becomes a multi-select!
It also includes a search with auto-complete by default. Here's how it looks:
Option 2. Create and Attach: Relation Managers
Filament also offers a function to create a related record immediately...