7 Easy Steps: Create Laravel 10 Livewire CRUD Operation

Websolutionstuff | Dec-06-2023 | Categories : Laravel MySQL

Hey there! I'm diving into the world of Laravel 10 and Livewire, and I'm excited to share a step-by-step guide on creating CRUD operations. Join me on this journey as we explore the simplicity of building powerful applications together. Let's make coding easy and fun.

In this article, we'll guide you through 7 easy steps to create laravel 9, and Laravel 10 Livewire CRUD operation.

Introduction to Laravel Livewire

Before we dive into the Laravel Livewire CRUD tutorial, let's first establish a basic understanding of Livewire.

What is Livewire?

Laravel Livewire is like a coding superhero that makes web development super easy! Imagine building interactive web features without writing a ton of JavaScript. Livewire lets you do just that, with simple, readable code. 

It's like magic for your Laravel projects, making them dynamic and user-friendly. Let's explore the world of Livewire together and simplify our development journey! ­čÜÇ

In this article, we'll guide you through implementing CRUD operations using Laravel Livewire. Discover all the necessary steps to seamlessly integrate Livewire into Laravel 10.

Step 1: Create a Laravel 10 Application

Create a new laravel 10 application using the following composer command.

composer create-project --prefer-dist laravel/laravel laravel-10-livewire-crud

cd laravel-10-livewire-crud

 

Step 2: Configure Database Details

Open .env file and configure DB_DATABASE, DB_USERNAME, and DB_PASSWORD.

.env

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

 

Step 3: Install the Livewire Package

Run the below command to install the livewire package.

composer require livewire/livewire

 

Step 4: Create Migration and Model

Create migration for the “posts” table and also we will create a model for the posts table.

php artisan make:migration create_posts_table

database/migrations

<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};

Run the below command to create a table in the database.

php artisan migrate

Now, we will create a post model using the below command.

php artisan make:model Post

Open app/Models/Post.php and replace it with the below code

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'description'
    ];
      public $timestamps = true;
}

 

 

Step 5: Create Post Component

Now we'll create a post component using the below command.

php artisan make:livewire post

The output of the above command is:

COMPONENT CREATED
CLASS: app/Http/Livewire/Post.php
VIEW:  resources/views/livewire/post.blade.php

Now, open app\Http\Livewire\Post.php and update the following code into that file:

<?php

namespace App\Livewire;

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

class Post extends Component
{
    public $posts, $title, $description, $postId, $updatePost = false, $addPost = false;
    
    protected $listeners = [
        'deletePostListner'=>'deletePost'
    ];
 
    protected $rules = [
        'title' => 'required',
        'description' => 'required'
    ];
 
    public function resetFields(){
        $this->title = '';
        $this->description = '';
    }

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

    public function createPost()
    {
        $this->resetFields();
        $this->addPost = true;
        $this->updatePost = false;
    }
     
    public function storePost()
    {
        $this->validate();
        try {
            Posts::create([
                'title' => $this->title,
                'description' => $this->description
            ]);
            session()->flash('success','Post Created Successfully!!');
            $this->resetFields();
            $this->addPost = false;
        } catch (\Exception $ex) {
            session()->flash('error','Something goes wrong!!');
        }
    }
     
    public function editPost($id){
        try {
            $post = Posts::findOrFail($id);
            if( !$post) {
                session()->flash('error','Post not found');
            } else {
                $this->title = $post->title;
                $this->description = $post->description;
                $this->postId = $post->id;
                $this->updatePost = true;
                $this->addPost = false;
            }
        } catch (\Exception $ex) {
            session()->flash('error','Something goes wrong!!');
        }
 
    }
     
    public function update()
    {
        $this->validate();
        try {
            Posts::whereId($this->postId)->update([
                'title' => $this->title,
                'description' => $this->description
            ]);
            session()->flash('success','Post Updated Successfully!!');
            $this->resetFields();
            $this->updatePost = false;
        } catch (\Exception $ex) {
            session()->flash('success','Something goes wrong!!');
        }
    }
     
    public function cancelPost()
    {
        $this->addPost = false;
        $this->updatePost = false;
        $this->resetFields();
    }
     
    public function deletePost($id)
    {
        try{
            Posts::find($id)->delete();
            session()->flash('success',"Post Deleted Successfully!!");
        }catch(\Exception $e){
            session()->flash('error',"Something goes wrong!!");
        }
    }
}

Then, Create resources/views/home.blade.php and update the following code into that file:

<!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>CRUD Operations Using Laravel Livewire - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    @livewireStyles
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">CRUD Operations Using Laravel Livewire - Websolutionstuff</a>
        </div>
    </nav>
    <div class="container">
        <div class="row justify-content-center mt-3">
            @livewire('post')
        </div>
    </div>
 
    @livewireScripts
</body>
// www.websolutionstuff.com
</html>

Now, Open resources/views/livewire/post.blade.php and update the following code into that file:

<div>
    <div class="col-md-8 mb-2">
        @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($addPost)
            @include('livewire.createPost')
        @endif
        @if($updatePost)
            @include('livewire.update')
        @endif
    </div>
    <div class="col-md-8">
        <div class="card">
            <div class="card-body">
                @if(!$addPost)
                <button wire:click="createPost()" class="btn btn-primary btn-sm float-right">Add New Post</button>
                @endif
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @if (count($posts) > 0)
                                @foreach ($posts as $post)
                                    <tr>
                                        <td>
                                            {{$post->title}}
                                        </td>
                                        <td>
                                            {{$post->description}}
                                        </td>
                                        <td>
                                            <button wire:click="editPost({{$post->id}})" class="btn btn-primary btn-sm">Edit</button>
                                            <button wire:click="deletePost({{$post->id}})" class="btn btn-danger btn-sm">Delete</button>
                                        </td>
                                    </tr>
                                @endforeach
                            @else
                                <tr>
                                    <td colspan="3" align="center">
                                        No Posts Found.
                                    </td>
                                </tr>
                            @endif
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

 

 

After that, we'll create two more files under resources/views/livewire/ one is createPost.blade.php, and the second is update.blade.php:

After creating the createPost.blade.php file replace the below content:

<div class="card">
    <div class="card-body">
        <form>
            <div class="form-group mb-3">
                <label for="title">Title:</label>
                <input type="text" class="form-control @error('title') is-invalid @enderror" id="title" placeholder="Enter Title" wire:model="title">
                @error('title')
                    <span class="text-danger">{{ $message }}</span>
                @enderror
            </div>
            <div class="form-group mb-3">
                <label for="description">Description:</label>
                <textarea class="form-control @error('description') is-invalid @enderror" id="description" 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="storePost()" class="btn btn-success btn-block">Save</button>
                <button wire:click.prevent="cancelPost()" class="btn btn-secondary btn-block">Cancel</button>
            </div>
        </form>
    </div>
</div>

After creating the update.blade.php file replace the below content:

<div class="card">
    <div class="card-body">
        <form>
            <div class="form-group mb-3">
                <label for="title">Title:</label>
                <input type="text" class="form-control @error('title') is-invalid @enderror" id="title" placeholder="Enter Title" wire:model="title">
                @error('title')
                    <span class="text-danger">{{ $message }}</span>
                @enderror
            </div>
            <div class="form-group mb-3">
                <label for="description">Description:</label>
                <textarea class="form-control @error('description') is-invalid @enderror" id="description" 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">Update</button>
                <button wire:click.prevent="cancelPost()" class="btn btn-secondary btn-block">Cancel</button>
            </div>
        </form>
    </div>
</div>

 

 

Step 6: Define Routes

Open routes/web.php and update the following code into that file:

Route::get('/',function(){
   return view('home');
});

 

Step 7: Run Laravel 10 Application

Now, run the laravel development server using the following command:

php artisan serve

 

Conclusion:

In conclusion, creating a Laravel 10 Livewire CRUD operation is a straightforward process that can greatly enhance the functionality of your web application.

By following the 7 easy steps outlined in the tutorial, you can seamlessly integrate Livewire components to perform Create, Read, Update, and Delete operations.

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Ajax File Upload With Progress Bar
Laravel 9 Ajax File Upload Wit...

In this article, we will see the laravel 9 ajax file upload with a progress bar. we will learn how to file upload using...

Read More

Nov-15-2022

Laravel 8 Has Many Through Relationship Example
Laravel 8 Has Many Through Rel...

In this example we will see laravel 8 has many through relationship example. hasManyThrough relationship difficult to un...

Read More

Nov-17-2021

How To Create Dark and Light Mode Website using jQuery
How To Create Dark and Light M...

In this article, we will see how to create a dark and light mode website using jquery. As you can see many websites and...

Read More

Nov-21-2020

Angular 13 Crop Image Before Upload With Preview
Angular 13 Crop Image Before U...

In this article, we will see the angular 13 crop image before uploading with a preview. we will give you a sim...

Read More

May-10-2022