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.
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 theProducts
table. You need to delete that migration. Otherwise, when creating a product, you will get an error. Don't forget to change theProductFactory
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...