Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Sharim's avatar

Parent and child category showing with Javascript

I have a checkout page where user will select his location. I stored all the states and areas in the database with parent_id. If customer select any state, the areas within this state should appear with javascript.

My State Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    protected $primaryKey = 'id';

    protected $fillable = ['name', 'prefix', 'id', 'parent_id'];

    public function children()
    {
       return $this->hasMany(State::class, 'parent_id', 'id');
    }
}

My Controller:

public function index()
{
$states = State::where('publish', true)->where('parent_id', null)->get();
return view('checkout')->with([
                'states' => $states
            ]);
}

My Blade View:

<select class="select_option" name="state" id="state" value="{{old('state')}}">
    <option value="{{old('state')}}" {{auth()->user()->state == "" ? 'selected':''}}>Select State: </option>
      @foreach($states as $state)
      <option value="{{ old('state') ?? $state->name}}" name="{{$state->name}}" {{old('state', auth()->user()->state)==$state->name ? 'selected':''}}> {{$state->name}} </option>
      
      @endforeach
</select>
//This part should appear when State Selected:
<select class="form-control select2 select2-hidden-accessible" name="area_id[]" multiple>
       @foreach($state->children as $state)
          <option class="form-control" value="{{$state->id}}"  > {{$state->name}} </option>
       @endforeach
       </select>
0 likes
4 replies
lat4732's avatar

Get the data with AJAX and display the results inside the select field.

lat4732's avatar
lat4732
Best Answer
Level 12

@Sharim

jQuery

$("#select_state_select_element").on('change', function() {

state_id = $(this).val();

$.ajax({
    url : 'URL ENDPOINT',
    type : 'GET/POST',
    data : {
        'state_id' : state_id
    },
    success : function(data) {              
        console.log(data);
    },
});

}

Your URL endpoint must return the results for the selected area.

Sharim's avatar

@Laralex Sir I'm doing like this:

$("#state").on('change', function() {

    state_id = $(this).val();
    
    $.ajax({
        url : '/state-checkout/'+state_id,
        method : 'POST',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data : {
            'state_id' : state_id
        },
        success : function(response) {  

            $.each(response.state, function(k, v){
                console.log(k + v);
            });        
            
        },
        error: function(data) {
            var errors = data.responseJSON;
            console.log(errors);
        }
    });

    });

in Controller:

public function state(Request $request)
    {
        $state = State::where('id', $request->state)->first();

        if (request()->ajax()) {
            
            return response()->json([
                'state' => $state->children,
            ]);
            
        }
    }

My route:

Route::post('/state-checkout/{state}', 'CheckoutController@state')->name('state.area');

I'm getting this in console.log:

0[object Object]

If I remove $.each() function, the results are showing good in an array. But I want a collection of states.

Please or to participate in this conversation.