laravel 11 dependent dropdown | websolutioncode.com
laravel 11 dependent dropdown | websolutioncode.com

Laravel 11 Dependent Dropdown

Introduction:

Dropdown menus are a common feature in web applications, allowing users to select options from a list. Laravel 11 Dependent Dropdown also known as cascading dropdowns, are a powerful extension of this concept. They dynamically populate options in one dropdown based on the selection in another, enhancing user experience and streamlining data selection. In this tutorial, we’ll explore how to implement Laravel 11 Dependent Dropdown, a popular PHP framework, using straightforward language and practical examples.

Prerequisites:

Before we dive into building dependent dropdowns, ensure you have the following:

  1. Basic understanding of PHP and Laravel.
  2. Composer installed globally on your system.
  3. Laravel 11 installed on your local environment.
  4. Familiarity with HTML and JavaScript.

Step 1:

Set Up Your Laravel Project If you haven’t already, create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel dependent-dropdown

Navigate to your project directory:

cd dependent-dropdown

Step 2:

Database Setup For this tutorial, we’ll use Laravel’s built-in SQLite database. Open the .env file and set the database connection:

DB_CONNECTION=sqlite

Next, create a SQLite database file:

touch database/database.sqlite

Step 3:

Create Models and Migration Let’s create two models: Country and City, along with their respective migrations:

php artisan make:model Country -m
php artisan make:model City -m

In the migration files, define the schema for both tables (countries and cities). For example:

// database/migrations/2024_05_01_create_countries_table.php

public function up()
{
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}

Repeat the same process for the cities table.

Step 4:

Define Relationships In Laravel, relationships between models are defined using Eloquent. Define a one-to-many relationship between Country and City:

// app/Models/Country.php

public function cities()
{
return $this->hasMany(City::class);
}
// app/Models/City.php

public function country()
{
return $this->belongsTo(Country::class);public function run()
{
\App\Models\Country::factory(5)->create()->each(function ($country) {
$country->cities()->saveMany(\App\Models\City::factory(3)->make());
});
}
}

Step 5:

Seed Data Seed the countries table with some sample data. Update the DatabaseSeeder class in database/seeders/DatabaseSeeder.php:

public function run()
{
\App\Models\Country::factory(5)->create()->each(function ($country) {
$country->cities()->saveMany(\App\Models\City::factory(3)->make());
});
}

Run the database migrations and seeders:

php artisan migrate --seed

Step 6:

Create Routes and Controller Define routes in routes/web.php to handle dropdown interactions and create a controller to manage the logic:

use App\Http\Controllers\DropdownController;

Route::get('/', [DropdownController::class, 'index']);
Route::get('/cities/{id}', [DropdownController::class, 'getCities']);

Generate the controller:

php artisan make:controller DropdownController

Step 7:

Implement Logic in Controller In the DropdownController, define methods to fetch countries and cities:

// app/Http/Controllers/DropdownController.php

public function index()
{
$countries = Country::pluck('name', 'id');
return view('dropdown', compact('countries'));
}

public function getCities($id)
{
$cities = City::where('country_id', $id)->pluck('name', 'id');
return json_encode($cities);
}

Step 8:

Create Blade View Create a Blade view to display the dropdowns and handle JavaScript:

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

<select id="country">
<option value="">Select Country</option>
@foreach($countries as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
@endforeach
</select>

<select id="city">
<option value="">Select City</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#country').change(function(){
var country_id = $(this).val();
$.get('/cities/' + country_id, function(cities){
$('#city').empty();
$.each(JSON.parse(cities), function(id, name){
$('#city').append($('<option>', {
value: id,
text: name
}));
});
});
});
</script>

Step 9:

Test Your Application Start the Laravel development server:

php artisan serve

Visit http://localhost:8000 in your browser to see the dependent dropdowns in action.

Conclusion:

In this tutorial, we’ve explored how to build Laravel 11 Dependent Dropdown, allowing users to select cities based on the chosen country dynamically. By following the step-by-step instructions and leveraging Laravel’s features such as Eloquent relationships and Blade templating engine, you can enhance the interactivity and usability of your web applications. Feel free to customize and expand upon this example to suit your specific requirements. Happy coding!