article

Wednesday, August 10, 2022

Laravel 9 Livewire CRUD (Create, Read, Update, Delete)

Laravel 9 Livewire CRUD (Create, Read, Update, Delete)

How to install laravel 9

https://tutorial101.blogspot.com/2022/02/how-to-install-laravel-9.html

Connecting our Database

open .env file root directory.

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

Livewire https://laravel-livewire.com/ is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.
Livewire completely sends Ajax requests to do all its server-side communication without writing any line of Ajax script.

Install Livewire Package:
C:\xampp\htdocs\laravel\laravelproject>composer require livewire/livewire

Create Model and Migration:
C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Post -m

laravelproject\database\migrations\create_post_table.php
laravelproject\database\migrations\create_post_table.php
//
<?php

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

return new class extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
Database Migration

php artisan migrate

C:\xampp\htdocs\laravel\laravelproject>php artisan migrate
Migration table created successfully.
check database table
Add Fillable Data in Model
app/Models/Post.php
//app/Models/Post.php
<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'description'
    ];

    public $timestamps = true;
}
Create Livewire Component and View
C:\xampp\htdocs\laravel\laravelproject>php artisan make:livewire post

open app\Http\Livewire\Post.php and update the following code
//app\Http\Livewire\Post.php
<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Post as Posts;

class Post extends Component
{
    public $posts, $name, $description, $post_id;
    public $updatePost = false;

    protected $listeners = [
        'deletePost'=>'destroy'
    ];

    // Validation Rules
    protected $rules = [
        'name'=>'required',
        'description'=>'required'
    ];

    public function render()
    {
        $this->posts = Posts::select('id','name','description')->get();
        return view('livewire.post');
    }

    public function resetFields(){
        $this->name = '';
        $this->description = '';
    }

    public function store(){

        // Validate Form Request
        $this->validate();

        try{
            // Create Post
            Posts::create([
                'name'=>$this->name,
                'description'=>$this->description
            ]);
    
            // Set Flash Message
            session()->flash('success','Post Created Successfully!!');

            // Reset Form Fields After Creating Post
            $this->resetFields();
        }catch(\Exception $e){
            // Set Flash Message
            session()->flash('error','Something goes wrong while creating post!!');

            // Reset Form Fields After Creating Post
            $this->resetFields();
        }
    }

    public function edit($id){
        $post = Posts::findOrFail($id);
        $this->name = $post->name;
        $this->description = $post->description;
        $this->post_id = $post->id;
        $this->updatePost = true;
    }

    public function cancel()
    {
        $this->updatePost = false;
        $this->resetFields();
    }

    public function update(){

        // Validate request
        $this->validate();

        try{

            // Update post
            Posts::find($this->post_id)->fill([
                'name'=>$this->name,
                'description'=>$this->description
            ])->save();

            session()->flash('success','Post Updated Successfully!!');
    
            $this->cancel();
        }catch(\Exception $e){
            session()->flash('error','Something goes wrong while updating post!!');
            $this->cancel();
        }
    }

    public function destroy($id){
        try{
            Posts::find($id)->delete();
            session()->flash('success',"Post Deleted Successfully!!");
        }catch(\Exception $e){
            session()->flash('error',"Something goes wrong while deleting post!!");
        }
    }
}
Create Views
laravelproject\resources\views\home.blade.php
//laravelproject\resources\views\home.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 9 Livewire CRUD (Create, Read, Update, Delete)</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
    @livewireStyles
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">Laravel 9 Livewire CRUD (Create, Read, Update, Delete)</a>
        </div>
    </nav>

    <div class="container">
        <div class="row justify-content-center mt-3">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header text-center">
                        <h2>Laravel 9 Livewire CRUD (Create, Read, Update, Delete)</h2>
                    </div>
                </div>
            </div>
        </div>
        <div class="row justify-content-center mt-3">
            @livewire('post')
        </div>
    </div>
    
    @livewireScripts
</body>
</html>
laravelproject\resources\views\livewire\post.blade.php
//laravelproject\resources\views\livewire\post.blade.php
<div>
    <div class="col-md-12 mb-2">
        <div class="card">
            <div class="card-body">
                @if(session()->has('success'))
                    <div class="alert alert-success" role="alert">
                        {{ session()->get('success') }}
                    </div>
                @endif

                @if(session()->has('error'))
                    <div class="alert alert-danger" role="alert">
                        {{ session()->get('error') }}
                    </div>
                @endif

                @if($updatePost)
                    @include('livewire.update')
                @else
                    @include('livewire.create')
                @endif
            </div>
        </div>
    </div>

    <div class="col-md-12">
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (count($posts) > 0)
                                @foreach ($posts as $rs)
                                    <tr>
                                        <td>
                                            {{$rs->name}}
                                        </td>
                                        <td>
                                            {{$rs->description}}
                                        </td>
                                        <td>
                                            <button wire:click="edit({{$rs->id}})" class="btn btn-primary btn-sm">Edit</button>
                                            <button onclick="deletePost({{$rs->id}})" class="btn btn-danger btn-sm">Delete</button>
                                        </td>
                                    </tr>
                                @endforeach
                            @else
                                <tr>
                                    <td colspan="3" align="center">
                                        No post Found.
                                    </td>
                                </tr>
                            @endif
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function deletePost(id){
            if(confirm("Are you sure to delete this record?"))
                window.livewire.emit('deletePost',id);
        }
    </script>
</div>
laravelproject\resources\views\livewire\create.blade.php
//laravelproject\resources\views\livewire\create.blade.php
<form>
    <div class="form-group mb-3">
        <label for="postName">Name:</label>
        <input type="text" class="form-control @error('name') is-invalid @enderror" id="postName" placeholder="Enter Name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group mb-3">
        <label for="postDescription">Description:</label>
        <textarea class="form-control @error('description') is-invalid @enderror" id="postDescription" wire:model="description" placeholder="Enter Description"></textarea>
        @error('description') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="d-grid gap-2">
        <button wire:click.prevent="store()" class="btn btn-success btn-block">Save</button>
    </div>
</form>
laravelproject\resources\views\livewire\update.blade.php
//laravelproject\resources\views\livewire\update.blade.php
<form>
    <input type="hidden" wire:model="post_id">
    <div class="form-group mb-3">
        <label for="postName">Name:</label>
        <input type="text" class="form-control @error('name') is-invalid @enderror" id="postName" placeholder="Enter Name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group mb-3">
        <label for="postDescription">Description:</label>
        <textarea class="form-control @error('description') is-invalid @enderror" id="postDescription" wire:model="description" placeholder="Enter Description"></textarea>
        @error('description') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="d-grid gap-2">
        <button wire:click.prevent="update()" class="btn btn-success btn-block">Save</button>
        <button wire:click.prevent="cancel()" class="btn btn-danger">Cancel</button>
    </div>
</form>
Route
laravelproject\routes\web.php
//laravelproject\routes\web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    //return view('welcome');
    return view('home');
});
Run C:\xampp\htdocs\laravel\laravelproject>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post