Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel Livewire CRUD with Jetstream & Tailwind CSS

Laravel Livewire CRUD with Jetstream & Tailwind CSS

Laravel 9 livewire crud example; In this tutorial, we will learn how to implement a crud application using livewire in laravel 9 apps.

Laravel Livewire CRUD with Jetstream & Tailwind CSS

Follow the following steps to make crud using livewire in laravel 9 apps:

  • Step 1 – Install Laravel 9 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 9 Application

Visit to local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel 9 latest application using the following command:

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

Step 2 – Configuring Database using Env File

Open downloaded laravel 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

Execute the following command on the command prompt to create model and migration file by using the following command:

php artisan make:model Post -m

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

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

Now, find Post.php model file inside /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 /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 terminal and type the following command on cmd to create tables into selected database:

php artisan migrate

Step 4 – Create Routes

Open 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

Execute following command on command prompt to install livewire package in laravel 9 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

Execute the following command on the command prompt to create livewire components in laravel 9 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

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

Go to 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 9 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 9 Livewire Crud - Tutsmake.com</h2>
                    </div>
                    <div class="card-body">
                        @livewire('posts')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
</html>

Step 8 – Start Development Server

Execute the following command on the command prompt to start the development server for laravel 9 livewire crud app:

php artisan serve

Step 9 – Run This App On Browser

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

http://127.0.0.1:8000/posts

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments