Laravel 7 Livewire Crud Example

Laravel livewire crud example tutorial. In this tutorial, you will learn how to implement livewire crud (create, read, update, delete) application using lara livewire package.

As well as learn how to validate laravel livewire forms, how to update livewire form data, and how to edit livewire form data in laravel.

This example demonstrates to you how to implement the user’s crud web application in laravel using livewire package.

Laravel Livewire Crud Example

Follow the following steps and create laravel crud application using livewire package with validation:

  • Step 1: Download Laravel Fresh App
  • Step 2: Setup Database Configuration
  • Step 3: Install Livewire
  • Step 4: Create Component
  • Step 5: Add Route
  • Step 6: Create Blade Views
  • Step 7: Run Development Server

Step 1: Download Laravel Fresh App

First of all, use the following command to install laravel fresh setup:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Setup Database Configuration

Next open, your project root directory and find .env file then update the following database details in your .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3: Install Livewire

Next step, install livewire package into your laravel application using the following command:

composer require livewire/livewire

Step 4: Create Component

Use the following command to create a component.

php artisan make:livewire users	

The above command will create two files on the following location:

app/Http/Livewire/Users.php
resources/views/livewire/users.blade.php

Open both file one by one and update the following code into your components files:

app/Http/Livewire/Users.php

<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\User;
class Users extends Component
{
    public $users, $name, $email, $user_id;
    public $updateMode = false;
    public function render()
    {
        $this->users = User::all();
        return view('livewire.users');
    }
    private function resetInputFields(){
        $this->name = '';
        $this->email = '';
    }
    public function store()
    {
        $validatedDate = $this->validate([
            'name' => 'required',
            'email' => 'required|email',
        ]);
        User::create($validatedDate);
        session()->flash('message', 'Users Created Successfully.');
        $this->resetInputFields();
    }
    public function edit($id)
    {
        $this->updateMode = true;
        $user = User::where('id',$id)->first();
        $this->user_id = $id;
        $this->name = $user->name;
        $this->email = $user->email;

    }
    public function cancel()
    {
        $this->updateMode = false;
        $this->resetInputFields();
    }
    public function update()
    {
        $validatedDate = $this->validate([
            'name' => 'required',
            'email' => 'required|email',
        ]);
        if ($this->user_id) {
            $user = User::find($this->user_id);
            $user->update([
                'name' => $this->name,
                'email' => $this->email,
            ]);
            $this->updateMode = false;
            session()->flash('message', 'Users Updated Successfully.');
            $this->resetInputFields();
        }
    }
    public function delete($id)
    {
        if($id){
            User::where('id',$id)->delete();
            session()->flash('message', 'Users Deleted Successfully.');
        }
    }
}

Step 5: Add Route

In this step, open routes/web.php file and add the following routes:

routes/web.php

Route::view('users','livewire.home');

Step 6: Create Blade Views

In this step, create following blade views file and update the following code into your files:

resources/views/livewire/users.blade.php

<div>
    @if($updateMode)
        @include('livewire.update')
    @else
        @include('livewire.create')
    @endif
    <table class="table table-bordered mt-5">
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $value)
            <tr>
                <td>{{ $value->id }}</td>
                <td>{{ $value->name }}</td>
                <td>{{ $value->email }}</td>
                <td>
                <button wire:click="edit({{ $value->id }})" class="btn btn-primary btn-sm">Edit</button>
                <button wire:click="delete({{ $value->id }})" class="btn btn-danger btn-sm">Delete</button>
                </td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

resources/views/livewire/home.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 Livewire CRUD Operation Tutorial From Scratch - tutsmake.com</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h2>Laravel Livewire Crud - tutmake.com</h2>
                    </div>
                    <div class="card-body">
                        @if (session()->has('message'))
                            <div class="alert alert-success">
                                {{ session('message') }}
                            </div>
                        @endif
                        @livewire('users')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>

resources/views/livewire/create.blade.php

<form>
    <div class="form-group">
        <label for="exampleFormControlInput1">Name</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter Name" wire:model="name">
        @error('name') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group">
        <label for="exampleFormControlInput2">Email address</label>
        <input type="email" class="form-control" id="exampleFormControlInput2" wire:model="email" placeholder="Enter Email">
        @error('email') <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>
    <div class="form-group">
        <input type="hidden" wire:model="user_id">
        <label for="exampleFormControlInput1">Name</label>
        <input type="text" class="form-control" wire:model="name" id="exampleFormControlInput1" placeholder="Enter Name">
        @error('name') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group">
        <label for="exampleFormControlInput2">Email address</label>
        <input type="email" class="form-control" wire:model="email" id="exampleFormControlInput2" placeholder="Enter Email">
        @error('email') <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 7: Run Development Server

In this step, use the following php artisan serve command to start your server locally:

php artisan serve

Now we are ready to run our example so run bellow command to quick run.

http://localhost:8000/users

Conclusion

In this livewire crud example, you have learned how to implement livewire crud web application in laravel using livewire pacagke.

Recommended Posts

  1. Laravel 7 Simple CRUD Example Tutorial
  2. Laravel 7 Ajax CRUD Example
  3. Laravel DataTables Ajax CRUD Tutorial Example
  4. Laravel Angular JS CRUD Example Tutorial
  5. Laravel 7 Crud with Image Upload From Scratch
  6. Laravel 7 Vue JS CRUD Example Tutorial

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *