If you are a Laravel developer then you will face a problem like click category show subcategory or click country and show state like that. This scenario is called a dynamic-dependent dropdown. We can easily create this Laravel-dependent dropdown using Ajax request. So this tutorial is going to show you how to create a dependent dropdown list in Laravel 10 using ajax.

In this tutorial, I will show you the dependent dropdown in Laravel 10 with Laravel jquery Ajax categories and subcategories select dropdown example. I will use parent_id to find out which is a subcategory and which is the parent category. Using category and subcategory, I will create this show subcategory by selecting the category Laravel using Ajax request.

Let's start the tutorial of dynamic dependent dropdown in Laravel 10 using jquery Ajax. I will use Laravel 10 version to create this dynamic-dependent dropdown example in Laravel.

 

Step 1: Download Fresh Laravel

In the first step of dynamic category and subcategory in Laravel example, download a fresh Laravel application by the following command:

composer create-project laravel/laravel example-app

 

Step 2: Create Model

In this second step, we need to create migration for the categories table using artisan command, so first fire bellow command:

php artisan make:model Category-m

 

Now update the Category model and migrations file.

App\Models\Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Category extends Model implements Auditable
{
    use HasFactory;

    protected $guarded = [];

    public function subcategories(){
        return $this->hasMany('App\Category', 'parent_id');
    }

}

 

Now update the migrations

<?php

use App\Models\Doctor;
use App\Models\Patient;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedInteger('parent_id')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('categories');
    }
};

 

Step 3: Connect database

In this step, we will connect the database, and I am going to use MySQL. So connect it like the below by updating the .env file:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

 

Now run the below command to generate a categories table:

php artisan migrate

 

Step 4:  Create Route

Now in this step, create a route like the one below to complete the category subcategory dropdown in the Laravel tutorial. I am going to use an Ajax request. So we can create this laravel dependent dropdown Ajax.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CategoryController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/


Route::controller(CategoryController::class)->group(function () {
    Route::get('/', 'index');
    Route::post('/subcat', 'show')->name('subcat');
});

 

Step 5: Create Controller

Now we have to create CategoryController to complete dependent dropdown in laravel 10. So run the below command to create a controller:

php artisan make:controller CategoryController

 

Now update this controller like this:

app/Http/Controllers/CategoryController.php

<?php

namespace App\Http\Controllers;

use App\Models\Event;
use Illuminate\Http\Request;

class EventController extends Controller
{
    public function index(Request $request)
    {
        $categoris = Category::where('parent_id',0)->get();
    
        return view('welcome',["categoris" => $categoris]);
    }

    public function show(Request $request)
    {
        $parent_id = $request->cat_id;
    
        $subcategories = Category::where('id',$parent_id)
                          ->with('subcategories')
                          ->get();

        return response()->json([
            'subcategories' => $subcategories
        ]);
    }
}

 

Step 6: Create Views

In this final step, we have to create an HTML form. So create it in the following path and update it like this:

resources/view/welcome.blade.php

<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel 10 Dynamic Dependent Dropdown Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<body>
    <div class="container" style="margin-top: 50px; margin-left: 300px">
        <div class="row">
            <div class="col-lg-6">
                <form action="">
                    <h4>Category</h4>
                    <select class="browser-default custom-select" name="category" id="category">
                        <option selected>Select category</option>
                        @foreach ($categoris as $item)
                            <option value="{{ $item->id }}">{{ $item->name }}</option>
                        @endforeach
                    </select>
                    <h4>Subcategory</h4>
                    <select class="browser-default custom-select" name="subcategory" id="subcategory">
                    </select>
                </form>

            </div>
        </div>
    </div>

    <script type="text/javascript">
        $(document).ready(function() {
            $('#category').on('change', function(e) {
                var cat_id = e.target.value;
                $.ajax({
                    url: "{{ route('subcat') }}",
                    type: "POST",
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        cat_id: cat_id
                    },
                    success: function(data) {
                        $('#subcategory').empty();
                        $.each(data.subcategories[0].subcategories, function(index,
                        subcategory) {
                            $('#subcategory').append('<option value="' + subcategory
                                .id + '">' + subcategory.name + '</option>');
                        })
                    }
                })
            });
        });
    </script>
</body>
</html>

 

Read also:  Laravel 10 Calendar Events With Ajax Tutorial

 

Conclusion

After completing this dynamic category and subcategory in laravel tutorial, hope now you know how to show subcategory by select category laravel. Hope this dependent dropdown in laravel 10 tutorial will help you.

Category : #laravel

Tags : #laravel , #laravel ajax