DeveloperBreeze

Dynamically Updating Form Fields with Livewire in Laravel

Dynamically Updating Form Fields with Livewire in Laravel

When building dynamic forms in Laravel, Livewire makes it easy to update form fields in real-time based on user interactions without needing to reload the page. In this tutorial, we'll walk through how to create a dynamic form where the options in a dropdown field are updated based on the selection of another field.

Prerequisites

  • Basic understanding of Laravel and Livewire
  • A Laravel project with Livewire installed

Objective

We'll create a form where the available options in a second dropdown field depend on the selection made in the first dropdown field.

Step 1: Setting Up the Livewire Component

First, let's create a Livewire component to handle our dynamic form.

Component Class

Run the following command to generate a Livewire component:

php artisan make:livewire DynamicForm

Open the newly created DynamicForm.php file and set up the properties and methods to manage the form fields:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class DynamicForm extends Component
{
    public $selectedCategory = null;
    public $subcategories = [];

    public function updatedSelectedCategory($category)
    {
        $this->subcategories = $this->getSubcategories($category);
    }

    public function getSubcategories($category)
    {
        // This is where you'd fetch subcategories from the database or an API based on the category
        $subcategoriesData = [
            'technology' => ['Web Development', 'Mobile Development', 'AI & ML'],
            'business' => ['Marketing', 'Finance', 'Entrepreneurship'],
            'design' => ['Graphic Design', 'UI/UX Design', '3D Modeling']
        ];

        return $subcategoriesData[$category] ?? [];
    }

    public function render()
    {
        return view('livewire.dynamic-form', [
            'categories' => ['technology', 'business', 'design']
        ]);
    }
}

Step 2: Creating the Blade View

Next, create the Blade view for this component in resources/views/livewire/dynamic-form.blade.php.

Blade Template

<div>
    <!-- Category Dropdown -->
    <label for="category">Category:</label>
    <select id="category" wire:model="selectedCategory">
        <option value="">Select a category</option>
        @foreach($categories as $category)
            <option value="{{ $category }}">{{ ucfirst($category) }}</option>
        @endforeach
    </select>

    <!-- Subcategory Dropdown -->
    @if(!empty($subcategories))
        <label for="subcategory" class="mt-4">Subcategory:</label>
        <select id="subcategory">
            <option value="">Select a subcategory</option>
            @foreach($subcategories as $subcategory)
                <option value="{{ $subcategory }}">{{ $subcategory }}</option>
            @endforeach
        </select>
    @endif
</div>

Step 3: Updating the Routes

Ensure your Livewire component is properly routed. Add the following to your web.php file:

use App\Http\Livewire\DynamicForm;

Route::get('/dynamic-form', DynamicForm::class);

Step 4: Testing the Form

Navigate to http://your-app-url/dynamic-form in your browser. You should see a dropdown for categories. When you select a category, the subcategory dropdown should populate with the corresponding options.

Explanation

  • Category Selection: The selectedCategory property is bound to the category dropdown. When a category is selected, the updatedSelectedCategory method is triggered.
  • Dynamic Subcategory Loading: The updatedSelectedCategory method calls getSubcategories to fetch the corresponding subcategories based on the selected category. The subcategories property is then updated, which dynamically updates the subcategory dropdown in the view.
  • Livewire Magic: Livewire automatically listens to the changes in the selectedCategory property and re-renders the relevant parts of the view without a full page reload.

Conclusion

Using Livewire to create dynamic forms is a powerful way to improve user experience by updating form fields in real-time based on user input. This tutorial demonstrated how to set up a dynamic dropdown menu in Laravel using Livewire, but the principles can be applied to any form field.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

Livewire Cheat Sheet: PHP & JavaScript Tips

   Livewire.emit('refreshComponent');
  • Target a specific component for an event:

Oct 24, 2024
Read More
Tutorial
javascript python

How to Build a Fullstack App with Flask and React

tasks = [
    {"id": 1, "title": "Task 1", "description": "This is task 1", "done": False},
    {"id": 2, "title": "Task 2", "description": "This is task 2", "done": True},
]

Now, add routes to retrieve, create, and delete tasks:

Sep 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

Use document.createElement to create a new element.

const newElement = document.createElement('div');
newElement.textContent = 'I am a new element!';

Aug 30, 2024
Read More
Tutorial
javascript php

Managing WYSIWYG Editors with Livewire: A Step-by-Step Guide

To ensure content is properly synchronized between the WYSIWYG editor and Livewire, you need to manage the communication between the two.

  • When users paste or type content into the editor, the onPaste and onChange callbacks emit a Livewire event (updateContent) with the new content.
  • The Livewire component listens for this event and updates the content property accordingly.

Aug 14, 2024
Read More
Tutorial
javascript php

Implementing Real-Time Search with Livewire in Laravel

Next, create the Blade view for this component in resources/views/livewire/search-posts.blade.php.

<div>
    <!-- Search Input -->
    <input type="text" placeholder="Search posts..." wire:model="query" class="border rounded p-2 w-full">

    <!-- Search Results -->
    @if(!empty($posts))
        <ul class="mt-4">
            @foreach($posts as $post)
                <li class="p-2 border-b">{{ $post->title }}</li>
            @endforeach
        </ul>
    @elseif(strlen($query) > 0)
        <p class="mt-4 text-gray-500">No results found for "{{ $query }}".</p>
    @endif
</div>

Aug 14, 2024
Read More
Tutorial
javascript php

Managing Modals with Livewire and JavaScript

We'll create a system to open and close modals using Livewire and JavaScript by dispatching custom events.

Create a Livewire component, or use an existing one where you want to manage modals.

Aug 14, 2024
Read More
AI Chat 1
Tailwind Component

AI Chat 1

No preview available for this content.

Jan 26, 2024
Read More
Code
javascript

Drag and Drop Event Handling in JavaScript

const draggableElement = document.getElementById('draggable');
draggableElement.addEventListener('dragstart', (event) => {
    event.dataTransfer.setData('text/plain', 'This is draggable');
});
draggableElement.addEventListener('dragend', () => {
    console.log('Drag operation completed');
});

Jan 26, 2024
Read More
Code
javascript

Event Emitter using 'events' module

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!