• Hello, Visitor
  • Monday, February 17, 2025
Search Result
Home » Laravel » Livewire » Laravel Livewire CRUD with Bootstrap Modal

Laravel Livewire CRUD with Bootstrap Modal

Video Tutorial:




Hello friends, in this blog, we would like to show you laravel 8 livewire crud operation example. we will implement a laravel 8 livewire crud application for beginners. We will give you simple example of how to create crud in laravel 8. you will learn crud operation in laravel 8 with livewire.

So, let's follow few step to create example of laravel 8 livewire crud application tutorial.

You just need to follow few step and you will get basic crud stuff using livewire component, model, route, bootstrap 4 and blade.

Now lets start,

Step 1: Create Laravel 8 Project
composer create-project --prefer-dist laravel/laravel LivewireCRUD

or,

laravel new LivewireCRUD


Step 2: Install Livewire in this Project

composer require livewire/livewire


Step 3: Database Configuration

Now we will make database configuration for example database name, username, password etc for our crud application of laravel 8 livewire. So let's open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=nzcoding_livewirecrud
DB_USERNAME=root
DB_PASSWORD=


Step 4: Make Student Model & Migration

php artisan make:model Student -m

go to database/migrations/student_table_migration & in up() function add the code

Schema::create('students', function (Blueprint $table) {
    $table->id();
    $table->string('student_id')->unique()->nullable();
    $table->string('name')->nullable();
    $table->string('email')->nullable();
    $table->string('phone')->nullable();
    $table->timestamps();
});

Now, migrate the migration

php artisan migrate


Step 5: Make Livewire Component

make base layout component

php artisan make:livewire layouts/base

make Students component

php artisan make:livewire StudentsComponent


Step 6: Add Get Route

Here, we need to add get route for students crud application. so open your "routes/web.php" file and add following route.

routes/web.php

use App\Http\Livewire\StudentsComponent;
use Illuminate\Support\Facades\Route;

Route::get('students', StudentsComponent::class);


Step 7: Add the Following Codes

Now, let's copy bellow code and put on StudentsComponent files,


resources/views/livewire/layouts/base.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>NzCoding - Laravel LivewireCRUD</title>

    {{-- Bootstrap Styles --}}
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

    @livewireStyles
</head>
<body>
   
    {{ $slot }}


    {{-- Bootstrap Scripts --}}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js"></script>

    @stack('scripts')
    @livewireScripts
</body>
</html>


app/Http/Livewire/StudentsComponent.php

<?php

namespace App\Http\Livewire;

use App\Models\Students;
use Livewire\Component;
use phpDocumentor\Reflection\Types\This;

class StudentsComponent extends Component
{
    public $student_id, $name, $email, $phone, $student_edit_id, $student_delete_id;

    public $view_student_id, $view_student_name, $view_student_email, $view_student_phone;

public $searchTerm;

    //Input fields on update validation
    public function updated($fields)
    {
        $this->validateOnly($fields, [
            'student_id' => 'required|unique:students,student_id,'.$this->student_edit_id.'', //Validation with ignoring own data
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|numeric',
        ]);
    }


    public function storeStudentData()
    {
        //on form submit validation
        $this->validate([
            'student_id' => 'required|unique:students', //students = table name
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|numeric',
        ]);

        //Add Student Data
        $student = new Students();
        $student->student_id = $this->student_id;
        $student->name = $this->name;
        $student->email = $this->email;
        $student->phone = $this->phone;

        $student->save();

        session()->flash('message', 'New student has been added successfully');

        $this->student_id = '';
        $this->name = '';
        $this->email = '';
        $this->phone = '';

        //For hide modal after add student success
        $this->dispatchBrowserEvent('close-modal');
    }

    public function resetInputs()
    {
        $this->student_id = '';
        $this->name = '';
        $this->email = '';
        $this->phone = '';
        $this->student_edit_id = '';
    }

    public function close()
    {
        $this->resetInputs();
    }

    public function editStudents($id)
    {
        $student = Students::where('id', $id)->first();

        $this->student_edit_id = $student->id;
        $this->student_id = $student->student_id;
        $this->name = $student->name;
        $this->email = $student->email;
        $this->phone = $student->phone;

        $this->dispatchBrowserEvent('show-edit-student-modal');
    }
   
    public function editStudentData()
    {
        //on form submit validation
        $this->validate([
            'student_id' => 'required|unique:students,student_id,'.$this->student_edit_id.'', //Validation with ignoring own data
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required|numeric',
        ]);

        $student = Students::where('id', $this->student_edit_id)->first();
        $student->student_id = $this->student_id;
        $student->name = $this->name;
        $student->email = $this->email;
        $student->phone = $this->phone;

        $student->save();

        session()->flash('message', 'Student has been updated successfully');

        //For hide modal after add student success
        $this->dispatchBrowserEvent('close-modal');
    }

    //Delete Confirmation
    public function deleteConfirmation($id)
    {
        $this->student_delete_id = $id; //student id

        $this->dispatchBrowserEvent('show-delete-confirmation-modal');
    }

    public function deleteStudentData()
    {
        $student = Students::where('id', $this->student_delete_id)->first();
        $student->delete();

        session()->flash('message', 'Student has been deleted successfully');

        $this->dispatchBrowserEvent('close-modal');

        $this->student_delete_id = '';
    }

    public function cancel()
    {
        $this->student_delete_id = '';
    }

    public function viewStudentDetails($id)
    {
        $student = Students::where('id', $id)->first();

        $this->view_student_id = $student->student_id;
        $this->view_student_name = $student->name;
        $this->view_student_email = $student->email;
        $this->view_student_phone = $student->phone;

        $this->dispatchBrowserEvent('show-view-student-modal');
    }

    public function closeViewStudentModal()
    {
        $this->view_student_id = '';
        $this->view_student_name = '';
        $this->view_student_email = '';
        $this->view_student_phone = '';
    }

    public function render()
    {
        //Get all students
        $students = Students::where('name', 'like', '%'.$this->searchTerm.'%')->orWhere('email', 'like', '%'.$this->searchTerm.'%')->orWhere('student_id', 'like', '%'.$this->searchTerm.'%')->orWhere('phone', 'like', '%'.$this->searchTerm.'%')->get();

        return view('livewire.students-component', ['students'=>$students])->layout('livewire.layouts.base');
    }
}


resources/views/livewire/layouts/base.blade.php

<div>
    <div class="container mt-5">
        <div class="row mb-5">
            <div class="col-md-12 text-center">
                <h3><strong>Laravel LivewireCRUD with Bootstrap Modal</strong></h3>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5 style="float: left;"><strong>All Students</strong></h5>
                        <button class="btn btn-sm btn-primary" style="float: right;" data-toggle="modal" data-target="#addStudentModal">Add New Student</button>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success text-center">{{ session('message') }}</div>
                        @endif

<div class="row mb-3">
                            <div class="col-md-12">
                                <input type="search" class="form-control w-25" placeholder="search" wire:model="searchTerm" style="float: right;" />
                            </div>
                        </div>

                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Phone</th>
                                    <th style="text-align: center;">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if ($students->count() > 0)
                                    @foreach ($students as $student)
                                        <tr>
                                            <td>{{ $student->student_id }}</td>
                                            <td>{{ $student->name }}</td>
                                            <td>{{ $student->email }}</td>
                                            <td>{{ $student->phone }}</td>
                                            <td style="text-align: center;">
                                                <button class="btn btn-sm btn-secondary" wire:click="viewStudentDetails({{ $student->id }})">View</button>
                                                <button class="btn btn-sm btn-primary" wire:click="editStudents({{ $student->id }})">Edit</button>
                                                <button class="btn btn-sm btn-danger" wire:click="deleteConfirmation({{ $student->id }})">Delete</button>
                                            </td>
                                        </tr>
                                    @endforeach
                                @else
                                    <tr>
                                        <td colspan="4" style="text-align: center;"><small>No Student Found</small></td>
                                    </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Leave a Reply

You must Login to add a comment