Laravel 8 Livewire CRUD Tutorial

Laravel 8 livewire crud example tutorial. In this post, i will share with you from scratch on how to build/make simple crud application using livewire in laravel 8.

Using the Laravel 8 Livewire package makes the crud operation very simple and easy.

So in this post, you will learn how to make a crud application using livewire in laravel 8.

Laravel 8 Livewire CRUD Example

  • Step 1 – Install Laravel 8 Application
  • Step 2 – Configuring Database using Env File
  • Step 3 – Create Post Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Installing Livewire Package
  • Step 6 – Build Livewire Components
  • Step 7 – Create Blade Views
  • Step 8 – Start Development Server
  • Step 9 – Run This App On Browser

Step 1 – Install Laravel 8 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 8 latest application using the following command:

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

Step 2 – Configuring Database using Env File

In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Create Post Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / Laravel8LivewireCrud

Then create model and migration file by using the following command:

php artisan make:model Post -m

The above command will create two files into your laravel 8 livewire crud application, which is located inside the following locations:

  • Laravel8LivewireCrud/app/Models/Post.php
  • Laravel8LivewireCrud/database/migrations/create_posts_table.php

Now, find Post.php model file inside Laravel8Crud/app/Models directory. And open it then add the fillable property code into Post.php file, like following:

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

Then, find create_posts_table.php file inside Laravel8LivewireCrud/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

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

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Livewire\Posts;

Route::get('posts', Posts::class);

Step 5 – Installing Livewire Package

In step 5, use the following command to install livewire package in laravel 8 app:

composer require livewire/livewire

Then install node js package:

npm install

Next run npm

npm run dev

Now, run database migration command:

php artisan migrate

Step 6 – Build Livewire Components

In step 6, use the following command to create livewire components in laravel 8 app:

php artisan make:livewire posts

The above command will create two files, which is located on the following locations:

app/Http/Livewire/Posts.php

resources/views/livewire/posts.blade.php

So, open Posts.php, which is located inside app/http/Livewire directory and add the following code into it:

<?php
  
namespace App\Http\Livewire;
  
use Livewire\Component;
use App\Models\Post;
  
class Posts extends Component
{
    public $posts, $title, $description, $post_id;
    public $isOpen = 0;
  
    /**
     * 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
     */
    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function openModal()
    {
        $this->isOpen = true;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function closeModal()
    {
        $this->isOpen = false;
    }
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    private function resetInputFields(){
        $this->title = '';
        $this->description = '';
        $this->post_id = '';
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function store()
    {
        $this->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
   
        Post::updateOrCreate(['id' => $this->post_id], [
            'title' => $this->title,
            'description' => $this->description
        ]);
  
        session()->flash('message', 
            $this->post_id ? 'Post Updated Successfully.' : 'Post Created Successfully.');
  
        $this->closeModal();
        $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->description = $post->description;
    
        $this->openModal();
    }
     
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function delete($id)
    {
        Post::find($id)->delete();
        session()->flash('message', 'Post Deleted Successfully.');
    }
}

Next, open posts.blade.php, which is located inside resources/views/livewire/ directory and add the following code into it:

<div>
    @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>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($posts as $value)
            <tr>
                <td>{{ $value->id }}</td>
                <td>{{ $value->title }}</td>
                <td>{{ $value->description }}</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>

Step 7 – Create Blade Views

In step 7, Navigate resources/views/livewire directory and create the following blade views:

  • Create.blade.php
  • Update.blade.php
  • Home.blade.php

Then add the following code into this files:

  • 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">Description</label>
        <input type="text" class="form-control" id="exampleFormControlInput2" wire:model="description" placeholder="Enter Description">
        @error('description') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <button wire:click.prevent="store()" class="btn btn-success">Save</button>
</form>
  • Update.blade.php
<form>
    <div class="form-group">
        <input type="hidden" wire:model="post_id">
        <label for="exampleFormControlInput1">Title</label>
        <input type="text" class="form-control" wire:model="title" id="exampleFormControlInput1" placeholder="Enter Title">
        @error('title') <span class="text-danger">{{ $message }}</span>@enderror
    </div>
    <div class="form-group">
        <label for="exampleFormControlInput2">Description</label>
        <input type="text" class="form-control" wire:model="description" id="exampleFormControlInput2" placeholder="Enter Description">
        @error('description') <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>
  • 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 8 Livewire CRUD Operation Tutorial From Scratch - laratutorials.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 8 Livewire Crud - laratutorials.com</h2>
                    </div>
                    <div class="card-body">
                        @livewire('posts')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>

Step 8 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your simple laravel 8 livewire crud app:

php artisan serve

Step 9 – Run This App On Browser

In step 9, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/posts

Leave a Comment