The Talent500 Blog
CRUD Operations Using Laravel Livewire 1

CRUD Operations Using Laravel Livewire

Before we begin with the Laravel Livewire CRUD tutorial, let us first grasp what Livewire is and how it is utilised.

 

What is Livewire?

Laravel Livewire allows you to create interfaces with the ease of Laravel. Livewire is a full-stack framework that reduces the complexity introduced by Vue or React. In February 2020, the first livewire version was launched.

In this blog, we will cover CRUD operations utilising Laravel Livewire, as well as all of the procedures required to install livewire in Laravel 9. Before that, you should consider upgrading from Laravel 8 to 9.

 

Setup and Prerequisites for Laravel Livewire CRUD Operations

Composer installed on your system (Just hit the “composer” command in the terminal to check whether the composer is properly installed or not). You may get Composer here (https://getcomposer.org/) if you don’t already have it.
How to Execute CRUD Operations Using Laravel Livewire?
We’ve seen how to use the Livewire package with the most recent Laravel version (v 9.19), and how to use it to perform the create, update, and delete operations in sequence.

 

1.Create a laravel Application

As you are already familiar with using a terminal to construct a laravel application, open a terminal and enter the following command to create a new laravel application in your directory.

composer create-project –prefer-dist laravel/laravel 

<application_name_here>


2.Configure Database Details

Open the.env file in the root folder; if.env does not exist, use the following command to create a copy from the.env-example.

cp .env .env-example

You must establish a new database with the same name as the one specified in DB DATABASE, as well as change the remainder of the.env variable with your system’s values.

DB_CONNECTION=mysql

    DB_HOST=127.0.0.1

    DB_PORT=3306

    DB_DATABASE=< DATABASE NAME >

    DB_USERNAME=< DATABASE USERNAME >

    DB_PASSWORD=< DATABASE PASSWORD >

 

3.To Install the Livewire Package

To install the livewire package, navigate to your application’s root directory and run the command below.

composer require livewire/livewire


We must include the livewire aesthetic and script (on every page that will be using Livewire).

&lt;head&gt;

    # other styles here

    @livewireStyles

    &lt;/head&gt;

    &lt;body&gt;

    # other body parts here

    @livewire(‘&lt;component name here&gt;’)/You can include component anywhere in your app

       @livewireScripts

    &lt;script src=”https://www.talent500.com/blog/wp-content/cache/min/1/c868d3b844e68cd780d4811c46215c40.js” data-minify=”1″ defer&gt;&lt;/script&gt;&lt;/body&gt;

4.Create Migration and Model

We will develop a migration for the “posts” database as well as a model for the posts table.

Please execute the command below to create a migration file. After running the command below, a new file will be generated in the database/migrations folder.

php artisan make:migration create_posts_table

 

In the create_posts_table migration file replace the below code:

&lt;?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-&gt;id();

            $table-&gt;string(‘title’)-&gt;nullable();

            $table-&gt;text(‘description’)-&gt;nullable();

            $table-&gt;timestamps();

        });

    }

 

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists(‘posts’);

    }

};

Run the following command to create a table in the database with the specified fields in migration. After performing the below command, you should notice a new “posts” table in the database.

php artisan migrate

Now, using the command below, we will construct a post model. After completing the following steps, you should be able to see a new model file in the app/Models folder:

php artisan make:model Post

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

&lt;?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;

}

5.Create Post component

Now, using the command below, we will construct a post component.

php artisan make:livewire post

After running the above script, you should notice a new Livewire folder under app/Http and resources/views.The Output for the above command is:

COMPONENT CREATED 

CLASS: app/Http/Livewire/Post.php

VIEW:  resources/views/livewire/post.blade.php

 

Now, open appHttpLivewirePost.php and add the following code to it:

&lt;?php

namespace App\Http\Livewire;

use Livewire\Component;

use App\Models\Post as Posts;

class Post extends Component

{

    public $posts, $title, $description, $postId, $updatePost = false, $addPost = false;

 

    /**

     * delete action listener

     */

    protected $listeners = [

        ‘deletePostListner’=&gt;’deletePost’

    ];

 

    /**

     * List of add/edit form rules 

     */

    protected $rules = [

        ‘title’ =&gt; ‘required’,

        ‘description’ =&gt; ‘required’

    ];

    /**

     * Reseting all inputted fields

     * @return void

     */

    public function resetFields(){

        $this-&gt;title = ”;

        $this-&gt;description = ”;

    }  

    /**

     * render the post data

     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View

     */

    public function render()

    {

        $this-&gt;posts = Posts::select(‘id’, ‘title’, ‘description’)-&gt;get();

        return view(‘livewire.post’);

    }

 

    /**

     * Open Add Post form

     * @return void

     */

    public function addPost()

    {

        $this-&gt;resetFields();

        $this-&gt;addPost = true;

        $this-&gt;updatePost = false;

    }

     /**

      * store the user inputted post data in the posts table

      * @return void

      */

    public function storePost()

    {

        $this-&gt;validate(); 

        try {

            Posts::create([

                ‘title’ =&gt; $this-&gt;title,

                ‘description’ =&gt; $this-&gt;description

            ]);

            session()-&gt;flash(‘success’,’Post Created Successfully!!’);

            $this-&gt;resetFields();

            $this-&gt;addPost = false;

        } catch (\Exception $ex) {

            session()-&gt;flash(‘error’,’Something goes wrong!!’);

        }

    }

 

    /**

     * show existing post data in edit post form

     * @param mixed $id

     * @return void

     */

    public function editPost($id){

        try {

            $post = Posts::findOrFail($id);

            if( !$post) {

                session()-&gt;flash(‘error’,’Post not found’);

            } else {

                $this-&gt;title = $post-&gt;title;

                $this-&gt;description = $post-&gt;description;

                $this-&gt;postId = $post-&gt;id;

                $this-&gt;updatePost = true;

                $this-&gt;addPost = false;

            }

        } catch (\Exception $ex) {

            session()-&gt;flash(‘error’,’Something goes wrong!!’);

        }   

    }

    /**

     * update the post data

     * @return void

     */

    public function updatePost()

    {

        $this-&gt;validate();

        try {

            Posts::whereId($this-&gt;postId)-&gt;update([

                ‘title’ =&gt; $this-&gt;title,

                ‘description’ =&gt; $this-&gt;description

            ]);

            session()-&gt;flash(‘success’,’Post Updated Successfully!!’);

            $this-&gt;resetFields();

            $this-&gt;updatePost = false;

        } catch (\Exception $ex) {

            session()-&gt;flash(‘success’,’Something goes wrong!!’);

        }

    }

 

    /**

     * Cancel Add/Edit form and redirect to post listing page

     * @return void

     */

    public function cancelPost()

    {

        $this-&gt;addPost = false;

        $this-&gt;updatePost = false;

        $this-&gt;resetFields();

    }

    /**

     * delete specific post data from the posts table

     * @param mixed $id

     * @return void

     */

    public function deletePost($id)

    {

        try{

            Posts::find($id)-&gt;delete();

            session()-&gt;flash(‘success’,”Post Deleted Successfully!!”);

        }catch(\Exception $e){

            session()-&gt;flash(‘error’,”Something goes wrong!!”);

        }

    }

}

Create resources/views/home.blade.php and add the following code to it:

&lt;!DOCTYPE html&gt;

&lt;html lang=”en”&gt;

&lt;head&gt;

    &lt;meta charset=”UTF-8″&gt;

    &lt;meta name=”viewport” content=”width=device-width, initial-scale=1.0″&gt;

    &lt;meta http-equiv=”X-UA-Compatible” content=”ie=edge”&gt;

    &lt;title&gt;Livewire Crud&lt;/title&gt;    

    &lt;link data-minify=”1″ href=”https://www.talent500.com/blog/wp-content/cache/min/1/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css?ver=1675427062″ rel=”stylesheet” crossorigin=”anonymous”&gt;

    @livewireStyles

&lt;/head&gt;

&lt;body&gt;

    &lt;nav class=”navbar navbar-expand-lg navbar-dark bg-dark”&gt;

        &lt;div class=”container-fluid”&gt;

            &lt;a class=”navbar-brand” href=”/”&gt;Livewire CRUD Blog&lt;/a&gt;

        &lt;/div&gt;

    &lt;/nav&gt;    

    &lt;div class=”container”&gt;

        &lt;div class=”row justify-content-center mt-3″&gt;

            @livewire(‘post’)

        &lt;/div&gt;

    &lt;/div&gt;

    @livewireScripts

&lt;script src=”https://www.talent500.com/blog/wp-content/cache/min/1/c868d3b844e68cd780d4811c46215c40.js” data-minify=”1″ defer&gt;&lt;/script&gt;&lt;/body&gt;

&lt;/html&gt;

Now, open resources/views/livewire/post.blade.php and insert the following code:

&lt;div&gt;

    &lt;div class=”col-md-8 mb-2″&gt;

        @if(session()-&gt;has(‘success’))

            &lt;div class=”alert alert-success” role=”alert”&gt;

                {{ session()-&gt;get(‘success’) }}

            &lt;/div&gt;

        @endif                

        @if(session()-&gt;has(‘error’))

            &lt;div class=”alert alert-danger” role=”alert”&gt;

                {{ session()-&gt;get(‘error’) }}

            &lt;/div&gt;

        @endif

        @if($addPost)

            @include(‘livewire.create’)

        @endif            

        @if($updatePost)

            @include(‘livewire.update’)

        @endif

    &lt;/div&gt;    

    &lt;div class=”col-md-8″&gt;

        &lt;div class=”card”&gt;

            &lt;div class=”card-body”&gt;

                @if(!$addPost)

                &lt;button wire:click=”addPost()” class=”btn btn-primary btn-sm float-right”&gt;Add New Post&lt;/button&gt;

                @endif

                &lt;div class=”table-responsive”&gt;

                    &lt;table class=”table”&gt;

                        &lt;thead&gt;

                            &lt;tr&gt;

                                &lt;th&gt;Name&lt;/th&gt;

                                &lt;th&gt;Description&lt;/th&gt;

                                &lt;th&gt;Action&lt;/th&gt;

                            &lt;/tr&gt;

                        &lt;/thead&gt;

                        &lt;tbody&gt;

                            @if (count($posts) &gt; 0)

                                @foreach ($posts as $post)

                                    &lt;tr&gt;

                                        &lt;td&gt;

                                            {{$post-&gt;title}}

                                        &lt;/td&gt;

                                        &lt;td&gt;

                                            {{$post-&gt;description}}

                                        &lt;/td&gt;

                                        &lt;td&gt;

                                            &lt;button wire:click=”editPost({{$post-&gt;id}})” class=”btn btn-primary btn-sm”&gt;Edit&lt;/button&gt;

                                            &lt;button onclick=”deletePost({{$post-&gt;id}})” class=”btn btn-danger btn-sm”&gt;Delete&lt;/button&gt;

                                        &lt;/td&gt;

                                    &lt;/tr&gt;

                                @endforeach

                            @else

                                &lt;tr&gt;

                                    &lt;td colspan=”3″ align=”center”&gt;

                                        No Posts Found.

                                    &lt;/td&gt;

                                &lt;/tr&gt;

                            @endif

                        &lt;/tbody&gt;

                    &lt;/table&gt;

                &lt;/div&gt;

            &lt;/div&gt;

        &lt;/div&gt;

    &lt;/div&gt;    

   

&lt;/div&gt;

We’ll need to add two additional files to resources/views/livewire/. The first one is create.blade.php, and the second is update.blade.php.

You can change the content in create.blade.php with the following

&lt;div class=”card”&gt;

    &lt;div class=”card-body”&gt;

        &lt;form&gt;

            &lt;div class=”form-group mb-3″&gt;

                &lt;label for=”title”&gt;Title:&lt;/label&gt;

                &lt;input type=”text” class=”form-control @error(‘title’) is-invalid @enderror” id=”title” placeholder=”Enter Title” wire:model=”title”&gt;

                @error(‘title’) 

                    &lt;span class=”text-danger”&gt;{{ $message }}&lt;/span&gt;

                @enderror

            &lt;/div&gt;

            &lt;div class=”form-group mb-3″&gt;

                &lt;label for=”description”&gt;Description:&lt;/label&gt;

                &lt;textarea class=”form-control @error(‘description’) is-invalid @enderror” id=”description” wire:model=”description” placeholder=”Enter Description”&gt;&lt;/textarea&gt;

                @error(‘description’) 

                    &lt;span class=”text-danger”&gt;{{ $message }}&lt;/span&gt;

                @enderror

            &lt;/div&gt;

            &lt;div class=”d-grid gap-2″&gt;

                &lt;button wire:click.prevent=”storePost()” class=”btn btn-success btn-block”&gt;Save&lt;/button&gt;

                &lt;button wire:click.prevent=”cancelPost()” class=”btn btn-secondary btn-block”&gt;Cancel&lt;/button&gt;

            &lt;/div&gt;

        &lt;/form&gt;

    &lt;/div&gt;

&lt;/div&gt;

 

You can replace it with following after creating update.blade.php 

 

&lt;div class=”card”&gt;

    &lt;div class=”card-body”&gt;

        &lt;form&gt;

            &lt;div class=”form-group mb-3″&gt;

                &lt;label for=”title”&gt;Title:&lt;/label&gt;

                &lt;input type=”text” class=”form-control @error(‘title’) is-invalid @enderror” id=”title” placeholder=”Enter Title” wire:model=”title”&gt;

                @error(‘title’) 

                    &lt;span class=”text-danger”&gt;{{ $message }}&lt;/span&gt;

                @enderror

            &lt;/div&gt;

            &lt;div class=”form-group mb-3″&gt;

                &lt;label for=”description”&gt;Description:&lt;/label&gt;

                &lt;textarea class=”form-control @error(‘description’) is-invalid @enderror” id=”description” wire:model=”description” placeholder=”Enter Description”&gt;&lt;/textarea&gt;

                @error(‘description’) 

                    &lt;span class=”text-danger”&gt;{{ $message }}&lt;/span&gt;

                @enderror

            &lt;/div&gt;

            &lt;div class=”d-grid gap-2″&gt;

                &lt;button wire:click.prevent=”updatePost()” class=”btn btn-success btn-block”&gt;Update&lt;/button&gt;

                &lt;button wire:click.prevent=”cancelPost()” class=”btn btn-secondary btn-block”&gt;Cancel&lt;/button&gt;

            &lt;/div&gt;

        &lt;/form&gt;

    &lt;/div&gt;

&lt;/div&gt;

6.Define Routes

Open routes/web.php and add the following code to it:

Route::get(‘/’,function(){

   return view(‘home’);

});

7.Run Project

Now that you’ve seen the above sample in the browser, open your terminal and run the following command from the project root directory.

php artisan serve

 

The following is the output of the preceding command:

 

Starting Laravel development server: http://127.0.0.1:8000

 

So, run your browser and go to the above-mentioned website.

 

Conclusion

We finished the laravel jetstream lesson, which detailed how to create crud operations with the livewire package. We also learned how to handle crud operations with the MySQL database.

 

Laravel Livewire is a powerful library that makes it easier for developers to create contemporary and dynamic interfaces with Laravel Blade. This stack is suitable for your next dynamic and interactive project.

 

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment