Livewire CRUD BootStrap 5 Modal Steps By Step Method for Laravel

In this tutorial we will show you that we can use bootstrap 5 modal when we have to use it with Livewire for our Laravel apps. We have explained with examples how we can easily manipulate the data using all three and get what we want.

We use Livewire which is a complete JavaScript framewok that helps developers to simplify complex interfaces as its a full-stack framework and all can be done within using it in the Laravel projects. Livewire uses AJAX for all server requests.

Now we have to follow all these steps and the first thing that we are supposed to do is to create our laravel project to invoke the changes. The whole guide and code used in it is pretty self explanatory but we have added comments on every stage as well so that it makes more sense to you.

#1 Create A New Laravel App Project

Let’s create a new Laravel project in our Laravel app.

composer create-project --prefer-dist laravel/laravel^9 Livewire-Bootstrap

Now we have introduces our project and we are going to build everything around it so that we can make its better use. For all your projects introducing the project is primary it makes sense to the IDE we are using.

#2 Let’s Configure Database Now

We need to configure our database once laravel project has been created and now our environment know that we want to build. For that we have to go to “.env” file and enter the database name we want with a user/password in it. We have using mysql database:

DB_CONNECTION=mysql

DB_HOST=192.0.0.1

DB_PORT=8080

DB_DATABASE=My_Database_Name

DB_USERNAME=My_DB_Username

DB_PASSWORD=My_DB_Password

Please note that your port and other details can be different it’s better to use your own so that you can make it work for your project the right way.

#3 Install Livewire

Use this command to install Livewire in our project as we are going to install livewire it will further move things to the edge for us to get it done the right way

composer require livewire/livewire

#4 Let’s Create A Livewire Component

We have to create Livewire component by using this command in our terminal:

php artisan make:livewire users

You will notice two separate files are created that need to be updated as well.

app/Http/Livewire/Users.php

resources/views/livewire/users.blade.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\User;

class Users extends Component
{
    public $users, $name, $email, $user_id;
    public $updateMode = false;
// In this part we will create the user and add other fields
    public function render()
    {
        $this->users = User::all();
        return view('livewire.users');
    }

    private function resetInputFields(){
        $this->name = '';
        $this->email = '';
    }

    public function store()
    {
        $validatedDate = $this->validate([
            'name' => 'required',
            'email' => 'required|email',
        ]);

        User::create($validatedDate);

        session()->flash('message', 'Congrats Users Added.');

        $this->resetInputFields();

        $this->emit('userStore'); // We close the modal now because we have to make use of jquery

    }
// we need to edit the data around our added user
    public function edit($id)
    {
        $this->updateMode = true;
        $user = User::where('id',$id)->first();
        $this->user_id = $id;
        $this->name = $user->name;
        $this->email = $user->email;
        
    }
// let's try the cancel function and add fields around it
    public function cancel()
    {
        $this->updateMode = false;
        $this->resetInputFields();


    }
// we will test the update function
    public function update()
    {
        $validatedDate = $this->validate([
            'name' => 'required',
            'email' => 'required|email',
        ]);

        if ($this->user_id) {
            $user = User::find($this->user_id);
            $user->update([
                'name' => $this->name,
                'email' => $this->email,
            ]);
            $this->updateMode = false;
            session()->flash('message', 'Congrats you have successfully update the data');
            $this->resetInputFields();

        }
    }
// we will test the delete function now
    public function delete($id)
    {
        if($id){
            User::where('id',$id)->delete();
            session()->flash('message', 'You have successfully deleted the added user');
        }
    }
}

#5 Now Add a Router

Now we need to add the router which is necessary as well
routes/web.php

Route::view('livewire bootstrap','livewire.main');

#6 We Will Create A View

Now we have to add view to our blade.php file to make modal calls and make use of @livewireStyles, @livewireScripts and @livewire(‘bootstrap-modal’) as well. We have shown the file in brief.
resources/views/livewire/bootstrap-modal.blade.php

<div>
    @include('livewire.create')
    @include('livewire.update')
    @if (session()->has('message'))
        <div class="alert alert-success" style="margin-right:25px;">x
          {{ session('message') }}
        </div>
    @endif
    <table class="table table-bordered mt-5">
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $value)
            <tr>
                <td>{{ $value->id }}</td>
                <td>{{ $value->name }}</td>
                <td>{{ $value->email }}</td>
                <td>
                <button data-toggle="modal" data-target="#updateModal" wire:click="edit({{ $value->id }})" class="btn btn-primary btn-sm">Edit</button>
                <button wire:click="delete({{ $value->id }})" class="btn btn-danger btn-sm">Delete</button>

resources/views/livewire/home.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Bootstrap Modal</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    @livewireStyles
</head>
// now let's add the container to it and define its components 
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h2>Laravel Livewire CRUD Modal - Laramatic- </h2>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('users')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
    <script type="text/javascript">
        window.livewire.on('userStore', () => {
            $('#exampleModal').modal('hide');
        });
    </script>
</body>
</html>

Let’s create the resource…blade.php file for the view: resources/views/livewire/create.blade.php

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
	Open Form
</button>
// Finally adding roles around modal
<!-- Modal -->
<div wire:ignore.self class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
    // now let's define the modal content including button
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="exampleModalLabel">Modal title</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     <span aria-hidden="true close-btn">×</span>
                </button>
            </div>
           // now we have to justify and add fields to the modal body 
           <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="exampleFormControlInput1">Name</label>
                        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Name" wire:model="name">
                        @error('name') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                  // We will form the group now 
                    <div class="form-group">
                        <label for="exampleFormControlInput2">Email address</label>
                        <input type="email" class="form-control" id="exampleFormControlInput2" wire:model="email" placeholder="Enter Email">
                        @error('email') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </form>
            </div>
// Adding fields to the modal footer
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary close-btn" data-dismiss="modal">Close</button>
                <button type="button" wire:click.prevent="store()" class="btn btn-primary close-modal">Store changes</button>
            </div>
        </div>
    </div>
</div>

Now going to update the created blade.php file

// lets update it now
<!-- Modal -->
<div wire:ignore.self class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
       <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="exampleModalLabel">Modal title</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <input type="hidden" wire:model="user_id">
                        <label for="exampleFormControlInput1">Name</label>
                        <input type="text" class="form-control" wire:model="name" id="exampleFormControlInput1" placeholder="Name">
                        @error('name') <span class="text-danger">{{ $message }}</span>@enderror
                    </div>
                    <div class="form-group">
                        <label for="exampleFormControlInput2">Email</label>
                        <input type="email" class="form-control" wire:model="email" id="exampleFormControlInput2" placeholder="Email">
                        @error('email') <span class="text-danger">{{ $message }}</span>@enderror
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" wire:click.prevent="cancel()" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" wire:click.prevent="update()" class="btn btn-primary" data-dismiss="modal">Save changes</button>
            </div>
       </div>
    </div>
</div>

Now our file is updated

Let’s run the server to test the changes in our Laravel project and check it our localhost

php artisan serve

Run this command ‘http://localhost:7000/bootstrap-modal’ to test the changes in the browser on the local server. Let’s know in the comments for all type of queries.
The result will show all the fields that we have created in this file once your run the server including Create, Edit, User Details etc.