Laravel 8 Jeatsream Livewire CRUD

Hay ..

Dalam tutorial ini saya akan membagikan sebuah tulisan mengenai cara membuat CRUD dengan livewire di Laravel 8

Pertama kita install project laravelnya terlebih dahulu

laravel new demo-laravel

1_3

Kedua, kita install untuk jeatsrem nya

composer require laravel/jetstream

Ketiga, kita install untuk livewire nya

php artisan jetstream:install livewire

Lalu kita jalankah perintah npm install dan npm run dev

Kemudian jalankan perintah php artisan migrate

Keempat, kita harus membuat sebuah migration dan model

php artisan make:migration create_blogs_table

database/migrations/2020_09_26_044246_create_blogs_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBlogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('blogs');
    }
}

jalankan perintah pada terminal, php artisan migrate

Kemudian kita membuat untuk modelnya

php artisan make:model Blog

App/Models/Blog.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'content',
    ];
}

Lalu kita buat untuk livewire nya

php artisan make:livewire blogs

maka akan ada 2 buah file baru

app/Http/Livewire/Blogs.php

resources/views/livewire/blogs.blade.php

app/Http/Livewire/Blogs.php kita tambahkan seperti dibawah ini

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Blog;

class Blogs extends Component
{

    public $blogs, $title, $content, $blog_id;
    public $isOpen = 0;

    public function render()
    {
        $this->blogs = Blog::all();
        return view('livewire.blogs');
    }

    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }

    public function openModal()
    {
        $this->isOpen = true;
    }

    public function closeModal()
    {
        $this->isOpen = false;
    }

    public function resetInputFields()
    {
        $this->title = '';
        $this->content = '';
        $this->blog_id = '';
    }

    public function store()
    {
        $this->validate([
            'title' => 'required',
            'content' => 'required'
        ]);

        Blog::updateOrCreate(['id' => $this->blog_id], [
            'title' => $this->title,
            'content' => $this->content
        ]);

        session()->flash(
            'message',
            $this->blog_id ? 'Blog Updated Successfully.' : 'Blog Created Successfully.'
        );

        $this->closeModal();
        $this->resetInputFields();
    }

    public function edit($id)
    {
        $blog = Blog::findOrFail($id);
        $this->blog_id = $id;
        $this->title = $blog->title;
        $this->content = $blog->content;

        $this->openModal();
    }

    public function delete($id)
    {
        Blog::find($id)->delete();
        session()->flash('message', 'Blog Deleted Successfully.');
    }
}

resources/views/livewire/blogs.blade.php seperti dibawah ini

<x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight">
        CRUD -- ASEPIT.COM
    </h2>
</x-slot>
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg px-4 py-4">
            @if (session()->has('message'))
                <div class="bg-teal-100 border-t-4 border-teal-500 rounded-b text-teal- 
                   900 px-4 py-3 shadow-md my-3" role="alert">
                  <div class="flex">
                    <div>
                      <p class="text-sm">{{ session('message') }}</p>
                    </div>
                  </div>
                </div>
            @endif
            <button wire:click="create()" class="bg-blue-500 hover:bg-blue-700 text- 
                white font-bold py-2 px-4 rounded my-3">Tambah</button>
            @if($isOpen)
                @include('livewire.create')
            @endif
            <table class="table-fixed w-full">
                <thead>
                    <tr class="bg-gray-100">
                        <th class="px-4 py-2 w-20">No.</th>
                        <th class="px-4 py-2">Title</th>
                        <th class="px-4 py-2">Content</th>
                        <th class="px-4 py-2">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($blogs as $blog)
                    <tr>
                        <td class="border px-4 py-2">{{ $blog->id }}</td>
                        <td class="border px-4 py-2">{{ $blog->title }}</td>
                        <td class="border px-4 py-2">{{ $blog->content }}</td>
                        <td class="border px-4 py-2">
                        <button wire:click="edit({{ $blog->id }})" class="bg-blue-500 
                           hover:bg-blue-700 text-white font-bold py-2 px-4 
                           rounded">Edit</button>
                         <button wire:click="delete({{ $blog->id }})" class="bg-red-500 
                           hover:bg-red-700 text-white font-bold py-2 px-4 
                           rounded">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

resources/views/livewire/create.blade.php ( kita tambahkan sebuah file bernama create.blade.php )

<div class="fixed z-10 inset-0 overflow-y-auto ease-out duration-400">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity">
            <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        <!-- This element is to trick the browser into centering the modal contents. -->
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen"></span>?
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow- 
             hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w- 
             lg sm:w-full" role="dialog" aria-modal="true" aria-labelledby="modal- 
             headline">
            <form>
                <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <div class="">
                        <div class="mb-4">
                            <label for="exampleFormControlInput1" class="block text- 
                               gray-700 text-sm font-bold mb-2">Title:</label>
                            <input type="text" class="shadow appearance-none border 
                               rounded w-full py-2 px-3 text-gray-700 leading-tight 
                               focus:outline-none focus:shadow-outline" 
                               id="exampleFormControlInput1" placeholder="Enter Title" 
                               wire:model="title">
                            @error('title') <span class="text-red-500">{{ $message }} 
                            </span>@enderror
                        </div>
                        <div class="mb-4">
                            <label for="exampleFormControlInput2" class="block text- 
                                        gray-700 text-sm font-bold mb-2">Content: 
                            </label>
                            <textarea class="shadow appearance-none border rounded w- 
                                             full py-2 px-3 text-gray-700 leading-tight 
                                             focus:outline-none focus:shadow-outline" 
                                             id="exampleFormControlInput2" 
                                             wire:model="content" placeholder="Enter 
                                             Content">
                            </textarea>
                            @error('content') <span class="text-red-500">{{ $message }} 
                            </span>@enderror
                        </div>
                    </div>
                </div>
                <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <span class="flex w-full rounded-md shadow-sm sm:ml-3 sm:w-auto">
                        <button wire:click.prevent="store()" type="button" 
                           class="inline-flex justify-center w-full rounded-md border 
                           border-transparent px-4 py-2 bg-green-600 text-base leading-6 
                           font-medium text-white shadow-sm hover:bg-green-500 
                           focus:outline-none focus:border-green-700 focus:shadow- 
                           outline-green transition ease-in-out duration-150 sm:text-sm 
                           sm:leading-5">
                           Save
                        </button>
                    </span>
                    <span class="mt-3 flex w-full rounded-md shadow-sm sm:mt-0 sm:w- 
                     auto">
                        <button wire:click="closeModal()" type="button" class="inline- 
                          flex justify-center w-full rounded-md border border-gray-300 
                          px-4 py-2 bg-white text-base leading-6 font-medium text-gray- 
                          700 shadow-sm hover:text-gray-500 focus:outline-none 
                          focus:border-blue-300 focus:shadow-outline-blue transition 
                          ease-in-out duration-150 sm:text-sm sm:leading-5">
                          Cancel
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>
</div>

routes/web.php

use App\Http\Livewire\Blogs;

Route::get('blog', Blogs::class);

php artisan serve

http://127.0.0.1:8000/blog

DONE !! 

Untuk demonya disini 

Semoga bermanfaat sebagai pengetahuan untuk kita semua, terutama bagi penulis sendiri

Related Articles

Comments