Debug School

rakesh kumar
rakesh kumar

Posted on

Explain lifecycle hooks methods using Livewire component for a CRUD

Perform crud operation using Livewire
Using mount, how to fetch data from db and display data using render method in blade file
Using wire:model="name" perform 2 way binding display and update data
How to change button name based on public variable isEditing
After update how to clear edited data using resetEdit
How to display data after submission of form in blade file
How to perform displaying and updating data in same html input element using mount

Create a Livewire Component:

php artisan make:livewire ItemComponent
Enter fullscreen mode Exit fullscreen mode

Define the Livewire Component:

// app/Http/Livewire/ItemComponent.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Item;

class ItemComponent extends Component
{
    public $items;
    public $name;
    public $selectedItem;
    public $isEditing = false;

    public function mount()
    {
        $this->items = Item::all();
    }

    public function render()
    {
        return view('livewire.item-component');
    }

    public function create()
    {
        Item::create(['name' => $this->name]);
        $this->name = '';
        $this->items = Item::all();
    }

    public function edit($itemId)
    {
        $this->selectedItem = Item::findOrFail($itemId);
        $this->name = $this->selectedItem->name;
        $this->isEditing = true;
    }

    public function update()
    {
        $this->selectedItem->update(['name' => $this->name]);
        $this->resetEdit();
    }

    public function delete($itemId)
    {
        $item = Item::findOrFail($itemId);
        $item->delete();
        $this->items = Item::all();
    }

    private function resetEdit()
    {
        $this->name = '';
        $this->selectedItem = null;
        $this->isEditing = false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Create the Blade View:

<!-- resources/views/livewire/item-component.blade.php -->

<div>
    <input type="text" wire:model="name">
    @if ($isEditing)
        <button wire:click="update">Update</button>
    @else
        <button wire:click="create">Create</button>
    @endif

    <ul>
        @foreach ($items as $item)
            <li>
                {{ $item->name }}
                <button wire:click="edit({{ $item->id }})">Edit</button>
                <button wire:click="delete({{ $item->id }})">Delete</button>
            </li>
        @endforeach
    </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

In this example:

mount() is used to fetch all items from the database when the component is first loaded.
create() method creates a new item in the database.
edit() method prepares the component for editing an item.
update() method updates the edited item in the database.
delete() method deletes an item from the database.
resetEdit() method resets the editing state of the component.
Enter fullscreen mode Exit fullscreen mode

These methods demonstrate how to perform CRUD operations in a Livewire component and utilize various lifecycle hooks and methods such as mount, render, updated, etc.

How to display data after submission of form in blade file

Step 1: Create a Livewire Component

Let's create a Livewire component to handle the form submission and display the submitted data.

// app/Http/Livewire/FormSubmission.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\FormData; // Import the model

class FormSubmission extends Component
{
    public $name;
    public $email;
    public $submittedData;

    protected $rules = [
        'name' => 'required|string',
        'email' => 'required|email',
    ];

    public function submitForm()
    {
        $this->validate();

        // Save the form data to the database
        FormData::create([
            'name' => $this->name,
            'email' => $this->email,
        ]);

        // Fetch all submitted data and store it for display
        $this->submittedData = FormData::all();

        // Clear form fields after submission
        $this->name = '';
        $this->email = '';
    }

    public function render()
    {
        return view('livewire.form-submission');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Blade View for the Component

Create a Blade view file where you define the form structure and display the submitted data.

<!-- resources/views/livewire/form-submission.blade.php -->

<div>
    <form wire:submit.prevent="submitForm">
        <div>
            <label for="name">Name:</label>
            <input type="text" wire:model="name" id="name">
            @error('name') <span>{{ $message }}</span> @enderror
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" wire:model="email" id="email">
            @error('email') <span>{{ $message }}</span> @enderror
        </div>
        <button type="submit">Submit</button>
    </form>

    <!-- Display submitted data -->
    @if($submittedData->count() > 0)
        <h2>Submitted Data:</h2>
        <ul>
            @foreach($submittedData as $data)
                <li>{{ $data->name }} - {{ $data->email }}</li>
            @endforeach
        </ul>
    @endif
</div>
Enter fullscreen mode Exit fullscreen mode

In this Blade view, we've defined a form with inputs for name and email. The wire:submit.prevent directive is used to prevent the default form submission behavior. After the form is submitted, the submitted data is displayed below the form.

Step 3: Run Your Application

Include the Livewire component in your application's Blade file or route as shown in the previous examples.

<!-- resources/views/welcome.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <!-- Include Livewire Scripts -->
    @livewireStyles
</head>
<body>
    <!-- Render the Livewire Component -->
    @livewire('form-submission')

    <!-- Include Livewire Scripts -->
    @livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now you can run your Laravel application. Fill in the form fields and click "Submit". The form data will be saved in the database, and the submitted data will be displayed below the form. The use of wire:click.prevent is implicit here because we're using wire:submit.prevent on the form. This prevents the default form submission behavior when the submit button is clicked.

How to perform displaying and updating data in same html input element

Below is a complete example that demonstrates how to display data from a database in input elements inside a form using Livewire. Additionally, you can update the data, and the updated data will be stored back in the database.

Step 1: Create a Livewire Component

Let's create a Livewire component to handle displaying and updating data.

// app/Http/Livewire/DataForm.php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\FormData; // Import the model

class DataForm extends Component
{
    public $name;
    public $email;
    public $formData;

    public function mount()
    {
        // Fetch data from the database and populate the form fields
        $this->formData = FormData::first();
        if ($this->formData) {
            $this->name = $this->formData->name;
            $this->email = $this->formData->email;
        }
    }

    public function updateFormData()
    {
        // Validate form data
        $this->validate([
            'name' => 'required|string',
            'email' => 'required|email',
        ]);

        // Update the data in the database
        if ($this->formData) {
            $this->formData->update([
                'name' => $this->name,
                'email' => $this->email,
            ]);
        } else {
            FormData::create([
                'name' => $this->name,
                'email' => $this->email,
            ]);
        }

        // Re-fetch the data to update form fields
        $this->mount();
    }

    public function render()
    {
        return view('livewire.data-form');
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Blade View for the Component

Create a Blade view file where you define the form structure and display the data.

<!-- resources/views/livewire/data-form.blade.php -->

<div>
    <form wire:submit.prevent="updateFormData">
        <div>
            <label for="name">Name:</label>
            <input type="text" wire:model="name" id="name">
            @error('name') <span>{{ $message }}</span> @enderror
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" wire:model="email" id="email">
            @error('email') <span>{{ $message }}</span> @enderror
        </div>
        <button type="submit">Update</button>
    </form>
</div>
Enter fullscreen mode Exit fullscreen mode

In this Blade view, we've defined a form with inputs for name and email. The wire:submit.prevent directive is used to prevent the default form submission behavior. The form data is bound to the component's properties using the wire:model directive.

Step 3: Run Your Application

Include the Livewire component in your application's Blade file or route as shown in the previous examples.

<!-- resources/views/welcome.blade.php -->

<!DOCTYPE html>
<html>
<head>
    <!-- Include Livewire Styles -->
    @livewireStyles
</head>
<body>
    <!-- Render the Livewire Component -->
    @livewire('data-form')

    <!-- Include Livewire Scripts -->
    @livewireScripts
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now you can run your Laravel application. The form fields will be populated with data from the database, and you can update the data by modifying the fields and clicking the "Update" button. The updated data will be stored back in the database.

Top comments (0)