Livewire CRUD, Livewire 3.0 tutorial, Laravel Livewire example, CRUD with Livewire, Laravel admin dashboard, Livewire pagination, Laravel customer management, Livewire form validation, Laravel Livewire modal, Laravel admin CRUD.

Livewire is a powerful framework for building dynamic interfaces in Laravel applications. It simplifies front-end interactivity by eliminating the need for complex JavaScript frameworks. In this guide, we’ll walk through creating a complete CRUD (Create, Read, Update, Delete) application using Livewire 3.0. Our example will manage customer data, including their name, phone, email, and address.

Prerequisites

Before diving in, ensure you have the following:

  • A Laravel application set up locally.
  • Basic understanding of Laravel and Livewire.
  • Livewire installed in your Laravel project.

To install Livewire, run:

composer require livewire/livewire

Step 1: Setting Up the Livewire Component

To start, we create a Livewire component for managing customers. Run the following command to generate it:

php artisan make:livewire Customers/Customer

This creates two files:

  1. Customer.php: The backend logic for the component.
  2. customer.blade.php: The front-end template for the component.

Step 2: Backend Logic

Below is the Customer.php file for handling CRUD operations.

Features:

  • Create: Add new customers.
  • Read: List customers with pagination and search functionality.
  • Update: Edit existing customer details.
  • Delete: Remove a customer from the database.
namespace App\Livewire\Customers;

use App\Models\CustomerData;
use Livewire\Component;
use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Auth;

class Customer extends Component
{
    use WithPagination, WithoutUrlPagination;

    public $name, $phone, $email, $address, $customerId;
    public $isEditMode = false;
    public $query = '';

    public $adminLogined;

    public function mount()
    {
        // Check if an admin is logged in
        if (Auth::guard('admin')->check()) {
            $this->adminLogined = Auth::guard('admin')->user();
        } else {
            $this->adminLogined = null;
        }
    }

    public function search()
    {
        $this->resetPage();
    }

    public function resetInputFields()
    {
        $this->name = '';
        $this->phone = '';
        $this->email = '';
        $this->address = '';
        $this->customerId = null;
        $this->isEditMode = false;
        $this->dispatch('close-modal');
    }

    public function store()
    {
        $this->validate([
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required|email|unique:customer_data,email',
            'address' => 'nullable',
        ]);

        CustomerData::create([
            'name' => $this->name,
            'phone' => $this->phone,
            'email' => $this->email,
            'address' => $this->address,
            'admin_id' => $this->adminLogined->id,
        ]);

        session()->flash('message', 'Customer added successfully.');
        $this->resetInputFields();
        $this->dispatch('closeModal');
    }

    public function edit($id)
    {
        $customer = CustomerData::findOrFail($id);
        $this->customerId = $customer->id;
        $this->name = $customer->name;
        $this->phone = $customer->phone;
        $this->email = $customer->email;
        $this->address = $customer->address;
        $this->isEditMode = true;
        $this->dispatch('openModal');
    }

    public function update()
    {
        $this->validate([
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required|email|unique:customer_data,email,' . $this->customerId,
            'address' => 'nullable',
        ]);

        $customer = CustomerData::findOrFail($this->customerId);
        $customer->update([
            'name' => $this->name,
            'phone' => $this->phone,
            'email' => $this->email,
            'address' => $this->address,
        ]);

        session()->flash('message', 'Customer updated successfully.');
        $this->resetInputFields();
        $this->dispatch('closeModal');
    }

    public function delete($id)
    {
        CustomerData::findOrFail($id)->delete();
        session()->flash('message', 'Customer deleted successfully.');
    }

    public function render()
    {
        $customers = CustomerData::where('admin_id', $this->adminLogined->id)
            ->where(function ($query) {
                $query->where('name', 'like', '%' . $this->query . '%')
                    ->orWhere('phone', 'like', '%' . $this->query . '%')
                    ->orWhere('email', 'like', '%' . $this->query . '%')
                    ->orWhere('address', 'like', '%' . $this->query . '%');
            })
            ->orderBy('id', 'desc')
            ->paginate(10);

        return view('livewire.customers.customer', [
            'customers' => $customers,
        ])->layout('components.layouts.app', ['title' => 'Customers']);
    }
}

Step 3: Frontend Implementation

In customer.blade.php, create a user-friendly interface with modals for adding and editing customers and a table for displaying customer data. Include search and pagination functionality to enhance usability.

Key Highlights:

  • Bootstrap for styling modals and tables.
  • Livewire directives for reactivity (e.g., wire:model, wire:click).
<div>
    <div class="page-header">
        <h2>Customer Management</h2>
        <button wire:click="resetInputFields" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#add-modal">Add Customer</button>
    </div>
    <div class="search-bar">
        <input type="text" placeholder="Search..." wire:model="query">
    </div>
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @forelse($customers as $customer)
                <tr>
                    <td>{{ $loop->iteration }}</td>
                    <td>{{ $customer->name }}</td>
                    <td>{{ $customer->phone }}</td>
                    <td>{{ $customer->email }}</td>
                    <td>
                        <button wire:click="edit({{ $customer->id }})" data-bs-toggle="modal" data-bs-target="#add-modal">Edit</button>
                        <button wire:click="delete({{ $customer->id }})">Delete</button>
                    </td>
                </tr>
            @empty
                <tr><td colspan="5">No customers found.</td></tr>
            @endforelse
        </tbody>
    </table>
    {{ $customers->links() }}
</div>

Step 4: Routing

Finally, add a route in web.php to render the component:

Route::get('/customers', App\Livewire\Customers\Customer::class)->name('customers');

Conclusion

Using Livewire 3.0, we created a fully functional CRUD application with minimal JavaScript. This approach is efficient and developer-friendly, allowing rapid prototyping and production-ready interfaces. Livewire’s power lies in its simplicity and seamless integration with Laravel.

Categorized in:

Blog, Laravel, Livewire,