Courses

Livewire 3 From Scratch: Practical Course

Multi-Select and belongsToMany Relationship

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Setting up many-to-many relationships
- Implementing multiple select functionality
- Managing selected values array
- Syncing relationships on save

In this lesson, we will see how to create multiple select input. We will change a category select dropdown from a single select to a multiple one.

multiple select form


DB Changes

Before making changes to the Livewire component, we need to make changes to the DB. First, we need a BelongsToMany relationship table.

database/migrations/xxxx_create_category_product_table.php:

Schema::create('category_product', function (Blueprint $table) {
$table->foreignId('category_id')->constrained()->cascadeOnDelete(;
$table->foreignId('product_id')->constrained()->cascadeOnDelete();
});

app/Models/Product.php:

use Illuminate\Database\Eloquent\Relations\BelongsToMany;
 
class Product extends Model
{
protected $fillable = [
'name',
'description',
'category_id',
'color',
'in_stock',
];
 
const COLOR_LIST = [
'red' => 'Red',
'green' => 'Green',
'blue' => 'Blue',
];
 
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
 
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}
}

Earlier, we added category_id to the Products table. You need to delete that migration. Otherwise, when creating a product, you will get an error. Don't forget to change the ProductFactory accordingly.

Also, I have changed the seeder to add two categories for each product.

$categories = collect(Category::pluck('id'));
Product::factory(50)
->create()
->each(function (Product $product) use ($categories) {
$product->categories()->sync($categories->random(2));
});

Livewire Component Changes

Now let's change the Products Livewire component to show multiple companies and fix...

The full lesson is only for Premium Members.
Want to access all 30 text lessons of this course? (108 min read)

You also get:

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