Tutorial Laravel Splade #7 - Delete Data dari Database


Rafi Taufiqurrahman
Cuma Hooman yang suka Laravel
Tutorial Laravel Splade #7 - Delete Data dari Database

Setelah berhasil melakukan update data baru sekarang kita akan belajar bersama-sama bagaimana caranya melakukan delete data dari database.

Langkah - 1 Menambahkan Method Destroy

Sekarang, silahkan teman-teman buka file app/Http/Controllers/PostController.php, kemudian ubah kode-nya sampai berikut ini :

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use ProtoneMedia\Splade\SpladeTable;

class PostController extends Controller
{
    /**
     * display all post data
     */
    public function index()
    {
        // get all post data
        $posts = Post::latest()->paginate(7);

        // render view
        return view('posts.index', [
            'posts' => SpladeTable::for($posts)
            ->column('image')
            ->column('title')
            ->column('content')
            ->column('action')
        ]);
    }

    /**
     *  display form create
     */
    public function create()
    {
        // render view
        return view('posts.create');
    }

    /**
     *  insert new post data
     */
    public function store(Request $request)
    {
        // validate request
        $this->validate($request, [
            'image'     => 'required|image|mimes:jpeg,jpg,png',
            'title'     => 'required|min:5',
            'content'   => 'required|min:10'
        ]);

        // upload image
        $image = $request->file('image');
        $image->storeAs('public/posts', $image->hashName());

        // insert new post to db
        Post::create([
            'title' => $request->title,
            'content' => $request->content,
            'image' => $image->hashName(),
        ]);

        // render view
        return redirect(route('posts.index'));
    }

    /**
     *  display form edit
     */
    public function edit(Post $post)
    {
        // render view
        return view('posts.edit', [
            'post' => $post
        ]);
    }

    /**
     *  update post data by id
     */
    public function update(Post $post, Request $request)
    {
        // validate request
        $this->validate($request, [
            'image'     => 'nullable|image|mimes:jpeg,jpg,png',
            'title'     => 'required|min:5',
            'content'   => 'required|min:10'
        ]);

        // update post data by id
        $post->update([
            'title' => $request->title,
            'content' => $request->content,
        ]);

        // check if user upload new image
        if($request->file('image')){
            // upload image
            $image = $request->file('image');
            $image->storeAs('public/posts', $image->hashName());

            // delete old image
            Storage::delete('public/posts/'. $post->image);

            // update post data image
            $post->update([
                'image' => $image->hashName(),
            ]);
        }

        // render view
        return redirect(route('posts.index'));
    }

    /**
     *  delete post data by id
     */
    public function destroy(Post $post)
    {
        // delete post image
        Storage::delete('public/posts/'. $post->image);

        // delete post data by id
        $post->delete();

        // render view
        return back();
    }
}

Dari perubahan kode di atas, kita menambahkan sebuah method baru dengan nama destroy dan di dalamnya kita lakukan route model binding dengan nama $post

/**
*  delete post data by id
*/
public function destroy(Post $post)
{
	// masukan kode disini...
}

Di dalam method tersebut pertama-tama kita melakukan hapus data gambar yang ada didalam folder storage/app/public/posts.

//delete post image
Storage::delete('public/posts/'. $post->image);

Setelah itu, kita lanjutkan dengan menghapus data post kita yang berada di dalam database kita.

// delete post data by id
$post->delete();

Jika proses hapus data berhasil dilakukan, maka kita akan melakukan render sebuah view dengan nama posts.index.

// render view
return back();

Langkah - 2 Menambahkan Button Delete

Silahkan teman-teman buka file yang bernama index.blade.php yang terletak di dalam folder resource/views/posts , kemudian masukan kode berikut ini :

<x-layout>
    <x-slot name="header">
        {{ __('Posts') }}
    </x-slot>
    <x-panel>
        <!-- btn create -->
        <div class="flex">
            <Link href="/posts/create"
                class="px-4 py-2 bg-gray-100 rounded-md text-sm border flex items-center gap-2 text-gray-700">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-circle-plus" width="24"
                height="24" viewBox="0 0 24 24" stroke-width="1.2" stroke="currentColor" fill="none"
                stroke-linecap="round" stroke-linejoin="round">
                <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                <path d="M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"></path>
                <path d="M9 12l6 0"></path>
                <path d="M12 9l0 6"></path>
            </svg>
            Add New Post
            </Link>
        </div>
        <!-- table component -->
        <x-splade-table :for="$posts">
            <x-slot:empty-state>
                <div class="flex text-center justify-center text-red-500">There are no items to show</div>
                </x-slot>
                @cell('image', $posts)
                    <img src="{{ asset('/storage/posts/' . $posts->image) }}" class="rounded-md w-1/3" />
                @endcell
                <!-- action button -->
                @cell('action', $posts)
                    <div class="flex gap-2">
                        <Link href="{{ route('posts.edit', $posts->id) }}"
                            class="rounded-full p-2 bg-orange-300 text-white hover:bg-orange-400">
                        <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-edit w-5 h-5"
                            width="24" height="24" viewBox="0 0 24 24" stroke-width="1.2" stroke="currentColor"
                            fill="none" stroke-linecap="round" stroke-linejoin="round">
                            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                            <path d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1"></path>
                            <path d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z"></path>
                            <path d="M16 5l3 3"></path>
                        </svg>
                        </Link>
                        <x-splade-form action="{{ route('posts.destroy', $posts->id) }}" confirm="Delete Data"
                            confirm-text="Are you sure you want to delete your post data?"
                            confirm-button="Yes, delete everything!" cancel-button="No, I want to stay!" method="delete">
                            <button type="submit" class="rounded-full p-2 bg-rose-300 text-white hover:bg-rose-400">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-trash w-5 h-5"
                                    width="24" height="24" viewBox="0 0 24 24" stroke-width="1.2"
                                    stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
                                    <path d="M4 7l16 0"></path>
                                    <path d="M10 11l0 6"></path>
                                    <path d="M14 11l0 6"></path>
                                    <path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12"></path>
                                    <path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3"></path>
                                </svg>
                            </button>
                        </x-splade-form>
                    </div>
                @endcell
        </x-splade-table>
    </x-panel>
</x-layout>

Dari penambahan kode diatas kita membuat sebuah form dari component splade form yang d mana action-nya kita arahkan ke dalam route yang bernama posts.destroy dan kita berikan paramater ID, kemudian route tersebut akan memanggil sebuah method destroy yang berada pada PostController kita. disini kita juga menambahkan beberapa attribute diantaranya confirm, confirm-text, confirm-button dan cancel-button.

<x-splade-form action="{{ route('posts.destroy', $posts->id) }}" confirm="Delete Data"
confirm-text="Are you sure you want to delete your post data?"
confirm-button="Yes, delete everything!" cancel-button="No, I want to stay!" method="delete">

	// masukan kode disini...
	
</x-splade-form>

Langkah - 3 Uji Coba Hapus Data Post

Silahkan teman-teman klik button dengan icon trash pada halaman posts.index, jika berhasil maka akan menampilkan sebuah component modal konfirmasi.

post-confirm

Silahkan klik, Yes, delete everything, maka data akan berhasil dihapus dari database.

post-delete

Oke sekian tutorial set kali ini, semoga bermafaat. Terimakasih Banyak.

Membangun Aplikasi Inventory Dengan Laravel & Tailwind CSS: https://santrikoding.com/ebook/membangun-aplikasi-inventory-dengan-laravel-tailwind-css?ref=8659VS4962

Membangun Website Online Course Dengan Laravel, Alpine.js dan Tailwind CSS: https://santrikoding.com/ebook/membangun-website-online-course-dengan-laravel-alpinejs-dan-tailwind-css?ref=8659VS4962


Rafi Taufiqurrahman
Cuma Hooman yang suka Laravel

Suka dengan tulisan di SantriKoding? Kamu bisa memberikan dukungan dengan berdonasi atau bagikan konten ini di sosial media. Terima kasih atas dukungan Anda!

KEBIJAKAN KOMENTAR

Saat memberikan komenatar silahkan memberikan informasi lengkap tentang error, seperti: screenshot, link kode, dll. Baca aturan komentar kami