Site Admin
Site Admin Founder of MeaningArticles
5191 Views

Laravel Livewire Select2 Multiple

Hello Dev.

in this article, I would love to share with you a way to inetegrate select2 livewire in laravel application. i'm able to display you a complete example for select2 multiple example with laravel livewire.

Livewire is a full-stack framework for Laravel that makes building dynamic interfaces easy, without leaving the comfort of Laravel. Livewire is predicated completely on AJAX requests to do all its server communicaton.

here i can supply complete instance for select2 in laravel livewire, So we could comply with the bellow step.


Step 1: Install Laravel App

In first step, We need to get fresh and new laravel application using bellow command. So Let's open terminal and run bellow command.

composer create-project --prefer-dist laravel/laravel blog


Step 2: Database Configuration

After successfully install laravel app then after configure databse setup. we will open .env file and change the database name, username and password in the env file.
.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password


Step 3: Install Livewire

In this step, You will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire


Step 4: Create Post Table

In this step, we have to create migration for products table using bellow artisan command. so let's open terminal and run bello command:

php artisan make:model Product -m

database/migrations/2021_07_21_044246_create_products_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('category');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

App/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = ['name','category'];
}


Step 5: Create Component

Now, you can create livewire component using bellow command, so Let's run bellow command to create Select2 form component:

php artisan make:livewire Select2

Now they created fies on both path:

app/Http/Livewire/Select2.php
resources/views/livewire/select2.blade.php

Now first file we will update as bellow for Select2.php file.
app/Http/Livewire/Select2.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Product;

class Select2 extends Component
{
    public $productList = [
        'Fruit',
        'Vegetable',
        'Chocolate',
        'Egg',
        'Fish',
        'Chemical',
        'Dairy Product',
    ];

    public $name,$category = [];

    public function render()
    {
        return view('livewire.select2');
    }

    public function store()
    {
        $input = [
            'name' => $this->name,
            'category' => json_encode($this->category),
        ];
        Product::create($input);
        $this->name = '';
        $this->category = '';
        $this->emit('productStore');
    }
}


Step 6: Add Route

now, we need to add route for create select2 dropdown and create product in laravel application. so open your "routes/web.php" file and add following route.
routes/web.php

Route::view('select2','livewire.home');


Step 7: Create View

Here, we will create blade file for call route. in this file we will use @livewireStyles, @livewireScripts and @livewire('posts'). so let's add it.
resources/views/livewire/home.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Select2 Multiple Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js" integrity="sha512-XKa9Hemdy1Ui3KSGgJdgMyYlUg1gM+QhL6cnlyTe2qzMCYm4nAZ1PsVerQzTTXzonUR+dmswHqgJPuwCq1MaAg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-P5MgMn1jBN01asBgU0z60Qk4QxiXo86+wlFahKrsQf37c9cro517WzVSPPV1tDKzhku2iJ2FVgL67wG03SGnNA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    @livewireStyles
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center mt-5">
            <div class="col-md-8 mt-5">
                <div class="card">
                    <div class="card-header bg-info text-white">
                        <h4>Laravel Livewire Select2 Multiple Example - meaningarticles.com</h4>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('select2')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
    @stack('scripts')
</body>
</html>
resources/views/livewire/select2.blade.php
<div>
    <form wire:submit.prevent="store">
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" wire:model="name" class="form-control">
                </div>
            </div>
            <div class="col-md-12">
                <div class="form-group">
                    <label>Category</label>
                    <div wire:ignore>
                        <select id="category-dropdown" class="form-control" multiple wire:model="category">
                            @foreach($productList as $product)
                                <option value="{{$product}}">{{ $product }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-md-12 text-center">
                <button type="submit" class="btn btn-success">Save</button>
            </div>
        </div>
    </form>
</div>
@push('scripts')
    <script>
        $(document).ready(function () {
            $('#category-dropdown').select2();
            $('#category-dropdown').on('change', function (e) {
                let data = $(this).val();
                 @this.set('category', data);
            });
            window.livewire.on('productStore', () => {
                $('#category-dropdown').select2();
            });
        });  
    </script>
@endpush

Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/select2

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.