Share this:

Today, We are going to learn how to Create Livewire CRUD Application in Laravel 9 Example. Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.

If you are using livewire then there is not use of Ajax and jQuery code to be written. Livewire help you to write Ajax and jQuery with very simple way in PHP. This will help you to submit the form, validation the inputs etc. without the page refresh.

In this tutorial we are going to create a application which will create, update, delete posts modules. Post with title and body field to create.

Also Read : Upload Images to Server PHP Tutorial (2022)

Steps to Create Livewire CRUD Application in Laravel 9 Example:

  • Step 1: Installing Fresh New Laravel 9
  • Step 2: Creating Migration
  • Step 3: Creating Model
  • Step 4: Installing Laravel Livewire
  • Step 5: Creating Post Component
  • Step 6: Updating Component File
  • Step 7: Updating Post Blade File
  • Step 8: Updating Welcome Blade File
  • Step 9: Testing
  • Step 10: Conclusion

Step 1: Installing Fresh New Laravel 9

First, We are going to install the fresh Laravel application using composer. To install a Laravel Application using composer open the terminal and run the following command:

composer create-project laravel/laravel livewire
cd livewire

livewire” is the project name.

Installing Fresh New Laravel 9
Installing Fresh New Laravel 9

Check out other way to install Laravel in Laravel Installation Docs.

Step 2: Creating Migration

Before creating Migration First create a database in phpmyadmin and add the details to .env file

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

Change the value as per your requirement.

Now, We are going to create database migration for “posts” table. To create a migration run the following code in terminal:

php artisan make:migration create_posts_table

add the following field to the posts migration table can be found at 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');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
};
Create database migration for posts table
Create database migration for posts table

Also Read : Laravel Load More Data on Scroll with jQuery and Ajax

Now, Run the migration this will create a table:

php artisan migrate
php artisan migrate
php artisan migrate

Step 3: Creating Model

Its time we will create model for files table. To create Post model file run the following command in terminal:

php artisan make:model Post

add the following code to the posts model can be found at 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;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title', 'body'
    ];
}
Create Post model file
Create Post model file

Step 4: Installing Laravel Livewire

Now, Its time to install livewire to our Laravel 9 Application. To Install livewire run the following command in terminal:

composer require livewire/livewire

Please check the requirements and other things in installation docs of livewire.

Also Read : Create a custom WordPress Plugin from scratch (2022)

Installing Laravel Livewire
Installing Laravel Livewire

Step 5: Creating Post Component

Now, We will create livewire Post Component for our Laravel CRUD Application. To create livewire post component run the following command in terminal:

php artisan make:livewire posts

The above command will create two file’s:

app/Http/Livewire/Posts.php
resources/views/livewire/posts.blade.php
Creating Post Component
Creating Post Component

Step 6: Updating Component File

So Now, we will write render(), resetInputFields(), store(), edit(), cancel(), update() and delete() method for our CRUD application. So, let, update following file.

app/Http/Livewire/Posts.php

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use App\Models\Post;
  
class Posts extends Component
{
    public $posts, $title, $body, $post_id;
    public $updateMode = false;
   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function render()
    {
        $this->posts = Post::all();
        return view('livewire.posts');
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields(){
        $this->title = '';
        $this->body = '';
    }
   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $validatedDate = $this->validate([
            'title' => 'required',
            'body' => 'required',
        ]);
  
        Post::create($validatedDate);
  
        session()->flash('message', 'Post Created Successfully.');
  
        $this->resetInputFields();
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function edit($id)
    {
        $post = Post::findOrFail($id);
        $this->post_id = $id;
        $this->title = $post->title;
        $this->body = $post->body;
  
        $this->updateMode = true;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function cancel()
    {
        $this->updateMode = false;
        $this->resetInputFields();
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function update()
    {
        $validatedDate = $this->validate([
            'title' => 'required',
            'body' => 'required',
        ]);
  
        $post = Post::find($this->post_id);
        $post->update([
            'title' => $this->title,
            'body' => $this->body,
        ]);
  
        $this->updateMode = false;
  
        session()->flash('message', 'Post Updated Successfully.');
        $this->resetInputFields();
    }
   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Post::find($id)->delete();
        session()->flash('message', 'Post Deleted Successfully.');
    }
}

Also Read : Create Custom Helper in CodeIgniter (2022)

Step 7: Updating Post Blade File

Now, We are going to create create, update and post list files in resources/views/livewire as you can seen in the below image.

Creating Create, Update, Post blade files
Creating Create, Update, Post blade files

Now add the code to the all the three files as follow:

resources/views/livewire/posts.blade.php

<div>
    @if (session()->has('message'))
        <div class="alert alert-success">
            {{ session('message') }}
        </div>
    @endif
  
    @if($updateMode)
        @include('livewire.update')
    @else
        @include('livewire.create')
    @endif
  
    <table class="table table-bordered mt-5">
        <thead>
            <tr>
                <th>No.</th>
                <th>Title</th>
                <th>Body</th>
                <th width="150px">Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($posts as $post)
            <tr>
                <td>{{ $post->id }}</td>
                <td>{{ $post->title }}</td>
                <td>{{ $post->body }}</td>
                <td>
                <button wire:click="edit({{ $post->id }})" class="btn btn-primary btn-sm">Edit</button>
                    <button wire:click="delete({{ $post->id }})" class="btn btn-danger btn-sm">Delete</button>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

This Post Blade file is used to show lists of post.

resources/views/livewire/create.blade.php

<form>
    <div class="form-group">
        <label for="exampleFormControlInput1">Title:</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
        @error('title') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group">
        <label for="exampleFormControlInput2">Body:</label>
        <textarea type="email" class="form-control" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
        @error('body') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <button wire:click.prevent="store()" class="btn btn-success">Save</button>
</form>

This Create Blade file is used to create a post.

resources/views/livewire/update.blade.php

<form>
    <input type="hidden" wire:model="post_id">
    <div class="form-group">
        <label for="exampleFormControlInput1">Title:</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Title" wire:model="title">
        @error('title') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group">
        <label for="exampleFormControlInput2">Body:</label>
        <textarea type="email" class="form-control" id="exampleFormControlInput2" wire:model="body" placeholder="Enter Body"></textarea>
        @error('body') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <button wire:click.prevent="update()" class="btn btn-dark">Update</button>
    <button wire:click.prevent="cancel()" class="btn btn-danger">Cancel</button>
</form>

This Update Blade is used to update the post.

Also Read : Integration PayPal Payment Gateway in PHP

Step 8: Updating Welcome Blade File

Now, We will update the default welcome.blade.php file to load our CRUD application in main webpage. we are adding bootstrap cdn in this example.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel 9 Livewire CRUD Application - LaravelTuts.com</title>
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" >
    </head>
    <body>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header">
                            <h2>Laravel 9 Livewire CRUD Application - LaravelTuts.com</h2>
                        </div>
                        <div class="card-body">
                            @if (session()->has('message'))
                                <div class="alert alert-success">
                                    {{ session('message') }}
                                </div>
                            @endif
                            @livewire('posts')
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @livewireScripts
    </body>
</html>

Step 9: Testing

So Now, Everything is done. You can test the Laravel Livewire CRUD Application. Run the following command in terminal to start the server:

php artisan serve

And, Open the following URL in browser:

http://127.0.0.1:8000

Create Post:

Create Livewire CURD Application in Laravel 9 Example
Create Livewire CRUD Application in Laravel 9 Example

Update Post:

Create Livewire CURD Application in Laravel 9 Example
Create Livewire CRUD Application in Laravel 9 Example

Delete Post:

Create Livewire CURD Application in Laravel 9 Example
Create Livewire CRUD Application in Laravel 9 Example

Step 10: Conclusion

Today, We had learn How to Create Livewire CRUD Application in Laravel 9 Example. Hope this tutorial helped you with learning Laravel 9 Livewire CRUD Application. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read : Drag & Drop Reorder Images in PHP (2022)

Share this:

Categorized in: