Laravel Livewire Crud Project

Laravel Livewire is front-end package for Laravel Framework with the help of Laravel Livewire you can run PHP script without using JavaScript! this package is a magical package for all PHP developers and the feature developers as well. So in this tutorial I will take you through how to create, Laravel Livewire CRUD(Create, Read, Update, and Delete),Completely Step by Step process. if you are new in Laravel Livewire I recommend you to read more about Laravel Livewire package. Laravel livewire doc

Outline of the project

  • We will setup our .env file for our database
  • We will define the route
  • We will create our migration file, and set the require attributes
  • we will make our model
  • we will make our view files
  • we will install Laravel Livewire
  • we will setup the layout file by providing the style and script from Livewire package

Step 1: Configure .Env File

To configure your database open .env file and set your database name and password

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Aw1WZs2xhd+8KSsSxVz8RtilNlYdA973q9IiFCbDGrs=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel-livewire
DB_USERNAME=root
DB_PASSWORD=''

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

Step 2: Define Route

We need to define our route file so that we will able to access our project in the browser, the route is located inside Routes/web.php and we will define our route like this below code.

Route::view('studentscrud','livewire.students.home');

Step 3: Create a Model

Create a student model class for database operation, use this below command to create a model.

php artisan make:model Student

The Student model is located inside App\Student.php write this below code there.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
   protected $fillable = ['firstname','lastname', 'gender', 'phone'];

   protected $primarykey = "id";
}

Step 4: Create Migration File

To create migration file use this below command

php artisan make:migration create_students_table

The migration file is located inside database/migration/create_students_table write this below code inside.

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('firstname', 50)->nullable();
            $table->string('lastname', 50)->nullable();
            $table->tinyInteger('gender')->default(1);
            $table->string('phone')->nullable();
            $table->timestamps();
        });
    }

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

Step 5: Run migration to migrate your tables to your database using this below command.

php artisan migrate

Step 6: Install Laravel livewire by using the below command

composer require livewire/livewire

Step 7: Include the Assets

Add the following Blade directives in the head tag, and before the end body tag in app.php located inside Resources/views/layout/app.php

<html>
<head>
    ...
    @livewireStyles
</head>
<body>
    ...
    @livewireScripts
</body>
</html>

Step 8: Making Components

Run the following artisan command to create a new Livewire component:

php artisan make:livewire StudentCrud

Two new files were created in your project:

  1. app/Http/Livewire/StudentCrud.php
  2. resources/views/livewire/student-crud.blade.php

Step 9: Inside the app/Http/Livewire/StudentCrud.php, put this flowing code inside.

<?php

namespace App\Http\Livewire;

use App\Student;
use Livewire\Component;

class StudentCrud extends Component
{
    public $data, $fname, $lname, $gender, $phone, $student_id, $search;
    public $UpdateStudent = false;

    public function render()
    {
        // $this->data = Student::all();
        $this->data = Student::where('firstname', 'like', '%'.$this->search.'%')
                                ->Orwhere('lastname', 'like', '%'.$this->search.'%')
                                ->Orwhere('gender', 'like', '%'.$this->search.'%')
                                ->get();
        return view('livewire.students.home');
    }


    protected $updatesQueryString = ['search'];

    public function mount()
    {
        $this->search = request()->query('search', $this->search);
    }

    // Saerch end here


    // reset star here
    function rest(){
        $this->fname = "";
        $this->lname = "";
        $this->phone = "";
        $this->gender = "Choose....";
    }

    // insert start here

    public function insert()
    {
        $this->validate([
            'fname' => 'required|min:3',
            'lname' => 'required|min:3',
            'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'gender' => 'required',
        ]);
        // here we will use our modal to insert our data into our database okay

       $student =  Student::create([
            'firstname' => $this->fname,
            'lastname' => $this->lname,
            'phone' => $this->phone,
            'gender' => $this->gender
        ]);

        // now we call the rest function okay
        $this->rest();
        session()->flash('message', 'Student successfully Created.');
    }

    // edit start here

    public function edit($id)
    {
        $record = Student::findOrFail($id);

        $this->student_id = $id;
        $this->fname = $record->firstname;
        $this->lname = $record->lastname;
        $this->gender = $record->gender;
        $this->phone = $record->phone;

        $this->UpdateStudent = true;
    }


    // update start here
    public function update()
    {
        $this->validate([
            'fname' => 'required|min:3',
            'lname' => 'required|min:3',
            'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            'gender' => 'required',
        ]);

        if ($this->student_id) {
            $record = Student::find($this->student_id);
            $record->update([
                'firstname' => $this->fname,
                'lastname' => $this->lname,
                'gender' => $this->gender,
                'phone' => $this->phone
            ]);

            $this->rest();
            $this->UpdateStudent = false;
            session()->flash('message', 'Student successfully updated.');
        }

    }


    // delete start here 
    public function destroy($id)
    {
        if ($id) {
            $record = Student::where('id', $id);
            $record->delete();
        }
    }
}

Step 10: Inside resources/views/livewire, create a folder name it students and inside the students folder create three files following the below list:

rosources
 views
   livewire
     students
      home.blade.php
      create-student.blade.php
      update-student.blade.php

Step 11: Add the following code inside home.blade.php:

    <div>

        {{-- @if (count($errors) > 0)
            <div class="alert alert-danger">
                <a href="#" class="close" data-dismiss="alert">×</a>
                <strong>Sorry!</strong> invalid input.<br><br>
                <ul style="list-style-type:none;">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif --}}
        <div class="navbar navbar-light bg-light" style="height: 10% !important">
        <div class=""><img src="{{asset('image/livewire.png')}}" style="height: 150px" alt=""></div>

        <div style="float:right;"><input type="text" wire:model="search"  class="form-control " placeholder="Search......"></div>
        {{-- <div style="float:right; " class="col-lg-1"> --}}
            {{-- <select name="sort" id="sortID" class="form-control">
                <option value="5">5</option>
                <option value="10">10</option>
                <option value="15">15</option>
                <option value="20">20</option>
        </select> --}}
    {{-- </div> --}}
</div>
    <br><br>
{{-- {{$search}} --}}
        @if($UpdateStudent)
            @include('livewire.contacts.update')
        @else
            @include('livewire.contacts.create')
        @endif

        <div class="table-responsive">
            <table class="table">
                <thead>
                    <th>#</th>
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Gender</th>
                    <th>Phone</th>
                    <th>Created date</th>
                    <th>Updated date</th>
                    <th colspan="3">Action</th>
                </thead>

            @foreach($data as $row)
                <tr>
                    <td>{{$row->id}}</td>
                    <td>{{$row->firstname}}</td>
                    <td>{{$row->lastname}}</td>
                    <td>{{$row->phone}}</td>
                    <td>@if ($row->gender== 0)male @else female @endif</td>
                    <td>{{$row->created_at->diffForHumans()}}</td>
                    <td>{{$row->updated_at->diffForHumans()}}</td>
                    <td>
                        <button wire:click="edit({{$row->id}})"class="btn btn-sm btn-info">Edit</button>
                        <button onclick="confirm('Are you sure! you want to delete this') || event.stopImmediatePropagation()"
                        wire:click="destroy({{$row->id}})" class="btn btn-sm btn-danger">Delete</button>
                    </td>
                </tr>
            @endforeach
        </table>

    </div>

Step 12: Add the following code inside create-student.blade.php:

<div >
    {{-- <form wire:submit.prevent="insert"> --}}
        <div class="form-row">
          <div class="form-group col-md-3">
            <label for="inputEmail4">First Name</label>
            <input wire:model="fname" type="text" class="form-control" id="inputEmail4" 
      placeholder="Enter Firstname">
            @error('fname') <span class="text-danger">{{ $message }}</span> @enderror
        </div>
          <div class="form-group col-md-3">
            <label for="inputPassword4">Last Name</label>
            <input type="text" wire:model="lname" class="form-control" id="inputPassword4" placeholder="Enter Lastname">
            @error('lname') <span class="text-danger">{{ $message }}</span> @enderror
        </div>

          <div class="form-group col-md-3">
            <label for="inputCity">Phone</label>
            <input type="text" wire:model="phone" class="form-control" placeholder="Enter Mobile">
            @error('phone') <span class="text-danger">{{ $message }}</span> @enderror
          </div>
          <div class="form-group col-md-2">
            <label for="inputState">Gender</label>
            <select id="inputState" wire:model="gender" class="form-control">
              <option selected>Choose...</option>
              <option value="0">Male</option>
              <option value="1">Female</option>
            </select>
            @error('gender') <span class="text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <button type="submit" wire:click.prevent="insert" style="float:right; margin-right:8%; margin-bottom:3px" class="btn btn-primary" >Create</button>
      {{-- </form> --}}
</div>


Step 13: Add the following code inside update-student.blade.php:

<div >
  
        <div class="form-row" wire:keydown.enter="update">
            <input type="hidden" wire:model="studentID">
          <div class="form-group col-md-3">
            <label for="inputEmail4">First Name</label>
            <input wire:model="fname" type="text" class="form-control"  placeholder="Enter Firstname">
            @error('fname') <span class="text-danger">{{ $message }}</span> @enderror
        </div>
          <div class="form-group col-md-3">
            <label for="inputPassword4">Last Name</label>
            <input type="text" wire:model="lname" class="form-control" placeholder="Enter Lastname">
            @error('lname') <span class="text-danger">{{ $message }}</span> @enderror
        </div>

          <div class="form-group col-md-3">
            <label for="inputCity">Phone</label>
            <input type="text" wire:model="phone" class="form-control" placeholder="Enter Mobile" >
            @error('phone') <span class="text-danger">{{ $message }}</span> @enderror
          </div>
          <div class="form-group col-md-2">
            <label for="inputState">Gender</label>
            <select id="inputState" wire:model="gender" class="form-control">
              <option selected>Choose...</option>
              <option value="0">Male</option>
              <option value="1">Female</option>
            </select>
            @error('gender') <span class="text-danger">{{ $message }}</span> @enderror
          </div>
        </div>
        <button type="submit" wire:click.prevent="update" style="float:right; margin-right:8%; margin-bottom:3px" class="btn btn-dark" >Update</button>
      
</div>

Step 14: Add the following code inside student-crud.blade.php:

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header bg-dark text-white"><b style="text-transform: uppercase">Student List</b>
                <div style="float:right"><input type="text" wire:model="search" wire:model="search"   class="form-control ml:1px" placeholder="Search......"></div>

                @if (session()->has('message'))
                        <div class="alert alert-success">
                            {{ session('message') }}
                        </div>
                    @endif
                </div>
                <div class="card-body">
                    @livewire('students-home')
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 15: Run the following code inside your terminal:

php artisan serve

in your browser type 127.0.0.1/studentscrud

The app is ready to use if you have any comment you can share it here to interact with the community thank you.

Published by jambasangsang

i am simple minded person who down to earth love making friendship in all part of the world.

Leave a comment