Install Laravel

First of all, we need to get a fresh Laravel application using the command below. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel laravel-app

Create Migration

In this step, we will create a migrations for categories and subcategories

Next, update the newly generated migration file contents database\migrations\2024_05_03_001817_create_categories.php. with the codes below.

<?php

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->timestamps();
        });

        Schema::create('sub_categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('category_id');
            $table->timestamps();
        });

    }

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

Then run the created new migration with the below command:

php artisan migrate

Create Models

In this step, we will create two models for the following tables Category.php, SubCategory.php model files.

Next, let’s run the commands below to create the models:

php artisan make:model Category
php artisan make:model SubCategory

Update your model files as below:

app/Models/Category.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Category extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name'
    ];
}

app/Models/SubCategory.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Category extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'category_id'
    ];
}

Create Seeder

In this step, we will create the “CategorySeeder” file to generate dummy records. So, let’s create the seeder and run it.

Create the Seeder file using the command below:

php artisan make:seeder CategorySeeder

Let’s update the following code in the seeder file:

database/seeders/CategorySeeder.php

<?php

namespace Database\Seeders;

use App\Models\Category;
use App\Models\SubCategory;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        //first category
        $category = Category::create(['name' => 'Electronics']);

        SubCategory::create(['category_id' => $category->id, 'name' => 'Clipper']);
        SubCategory::create(['category_id' => $category->id, 'name' => 'Laptop']);
        SubCategory::create(['category_id' => $category->id, 'name' => 'Fridge']);
        SubCategory::create(['category_id' => $category->id, 'name' => 'laptop']);

        //second category
        $category = Category::create(['name' => 'Fashion']);

        SubCategory::create(['category_id' => $category->id, 'name' => 'Trouser']);
        SubCategory::create(['category_id' => $category->id, 'name' => 'Shirt']);

        //third category
        $category = Category::create(['name' => 'Sports']);

        SubCategory::create(['category_id' => $category->id, 'name' => 'Ball']);
        SubCategory::create(['category_id' => $category->id, 'name' => 'Whistle']);
    }
}

Next, run the seeder with the below command:

php artisan db:seed --class=CategorySeeder

Create Controller

In this step, we have to create a new controller as CategoryController with index() and fetchSubCategories().

Next, run the seeder with the below command:

php artisan make:controller CategoryController

So let’s update the following code:

app/Http/Controllers/CategoryController.php

<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\SubCategory;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index()
    {
        $data['categories'] = Category::get(["name", "id"]);

        return view('categories', $data);
    }

    public function fetchSubCategories(Request $request)
    {
        $data['categories'] = SubCategory::where("category_id", $request->category_id)
            ->get(["name", "id"]);

        return response()->json($data);
    }
}

Create Routes

In this step, we will add three routes with GET and POST methods in routes/web.php file. So let’s add it.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\CategoryController;
    
Route::get('categories', [CategoryController::class, 'index']);
Route::post('fetch-subcategories', [CategoryController::class, 'fetchSubCategories'])->name('fetchSubCategories');

Step 7: Create View File

In the last step, let’s create dropdown.blade.php to display the form and insert the following code:

resources/views/categories.blade.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel AJAX Dependent with select - Tehbly.ng</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
    <div class="container mt-4">
        <div class="card mt-5">
            <h3 class="card-header p-3">Laravel AJAX Dependent form select - techbly.ng</h3>
            <div class="card-body">
                <form>
                    <div class="form-group mb-3">
                        <select id="category_id" class="form-control">
                            <option value="">-- Select Country --</option>
                            @foreach ($categories as $category)
                                <option value="{{ $category->id }}">
                                    {{ $category->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <select id="sub_category_id" class="form-control">
                        </select>
                    </div>

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

    <script type="text/javascript">
        $(document).ready(function() {


            $('#category_id').on('change', function() {

                var category_id = this.value;

                $("#sub_category_id").html('');

                $.ajax({
                    url: "{{ route('fetchSubCategories') }}",
                    type: "POST",
                    data: {
                        category_id: category_id,
                        _token: '{{ csrf_token() }}'
                    },
                    dataType: 'json',
                    success: function(result) {

                        $.each(result.categories, function(key, value) {
                            $("#sub_category_id").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                    }
                });
            });

        });
    </script>
</body>

</html>

Run Laravel App:

After completing the steps above, you have to run the command below and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

Chiwetara Igwe

I'm a full-stack developer, entrepreneur and owner of techbly.ng. I live in Nigeria and I love to write tutorials and tips that can help to other web developers. I am experienced in PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap. I am passionate about learning new things and keeping up with the latest trends and technologies.

http://techbly.ng

Leave a Reply

Your email address will not be published. Required fields are marked *

× Have a question?