Laravel Livewire CRUD Application Example

Laravel Livewire CRUD Application Example

I will explain a step-by-step tutorial on how to create a Laravel Livewire CRUD Application Example. This is a simple example that demonstrates how to use Livewire with Laravel to create a CRUD application. You can follow along with this Livewire Laravel tutorial example. If you’re looking for an example of Livewire CRUD with Laravel , then you’re in the right place. So let’s dive into the details!.

What is Livewire ?

Livewire is an open-source library for Laravel, a popular PHP web application framework. It allows developers to build dynamic, reactive interfaces in Laravel using a syntax that is similar to writing Blade templates. With Livewire, developers can create interactive user interfaces without the need for additional JavaScript code. Livewire works by enabling the server to push changes to the client-side, allowing for dynamic updates to the interface without requiring a page refresh. You Can Learn Laravel 11 Drag and Drop File Upload with Dropzone JS

Livewire provides a number of pre-built components, such as forms and modals, that make it easy to create complex user interfaces quickly. Developers can also create their own custom components to suit their specific needs.

In this example, we will create a module for inserting, updating, and deleting posts. We will include fields for the post title and body, allowing you to create, update, and delete posts.

Laravel Livewire CRUD Application Example

Laravel Livewire CRUD Application Example

So, let’s follow the bellow step and you will get bellow layout:

List View:

Laravel Livewire CRUD Application

Create View:

Laravel Livewire CRUD Application

Update View:

Laravel Livewire CRUD Application

Step 1: Install Laravel 10

first of all we need to get fresh Laravel 10 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project laravel/laravel livewire

Step 2: Create Migration and Model

Here, we need create database migration for “posts” table and also we will create model for files table.

php artisan make:migration create_posts_table

Migration:

<?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(): void
{

Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->timestamps();

});

}



/**

* Reverse the migrations.
*
* @return void
*/
public function down(): void

{
Schema::dropIfExists('posts');
}

};
php artisan migrate

now we will create “Post” model by using following command:

php artisan make:model Post

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'
    ];

}

Step 3: Install Livewire

now in this step, we will simply install livewire to our laravel application using bellow command:

composer require livewire/livewire

Step 4: Create Post Component

Now here we will create livewire component using their command. so run bellow command to create post crud application component.

php artisan make:livewire posts

Now they created fies on both path:

app/Http/Livewire/Posts.php

resources/views/livewire/posts.blade.php

Step 4: Update Component File

Here, we will write render(), resetInputFields(), store(), edit(), cancel(), update() and delete() method for our crud app.

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::latest()->get();
        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.');

    }

}

Step 5: Update Blade Files

Here, we will update following list of files for our listing page, create page and update page.

So, let’s update all the files as bellow:

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>

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>

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>

Step 6: Update Welcome Blade File

We will update laravel welcome blade file so it will load crud example on our main url.

here, we will update welcome.blade.php file. in this file we will use @livewireStyles, @livewireScripts and @livewire(‘contact-form’). so let’s add it.

resources/views/welcome.blade.php

<!DOCTYPE html>

<html>

<head>

    <title>Laravel Livewire CRUD - DevScriptSchool.com</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

    @livewireStyles

</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 Livewire CRUD - DevScriptSchool.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>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/

Leave a Reply