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

luk's avatar
Level 1

updating the options of the "admin_id" select element

In my project i want to create difference admins for colleges ,departments and laboratorys , i u used Ajax for fetching data of admin id depends on the admin type input and i also use a logic in controller as the following in my controller :


    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|',
            'password' => 'required',
            'roles' => 'required',
            'admin_type'=>'required',
            'admin_id'=>'required'

            
        ]);
        $adminType = $request->input('admin_type');
        $adminId = $request->input('admin_id');
        $input = $request->all();
        // $input['password'] = Hash::make($input['password']);
    
        $user = User::create($input);
        if ($adminType == 'colleges') {
            $user->colleges()->attach($adminId);
        } else if ($adminType == 'departments') {
            $user->departments()->attach($adminId);
        } else if ($adminType == 'laboratories') {
            $user->laboratories()->attach($adminId);
        }
        $user->assignRole($request->input('roles'));
    
        return redirect()->route('users.index')
                        ->with('success','User created successfully');
    }
 public function getAdminId(Request $request)//for getting admin ids depends on the admin_type
{
    $adminType = $request->admin_type;
    $options = '';

    if ($adminType == 'college') {
        $colleges = College::all();
        foreach ($colleges as $college) {
            $options .= '<option value="'.$college->id.'" id="'.$college->id.'">'.$college->name.'</option>';
         }
         
    } elseif ($adminType == 'department') {
        $departments = Department::all();
        foreach ($departments as $department) {
            $options .= '<option value="'.$department->id.'">'.$department->name.'</option>';
        }
    } elseif ($adminType == 'laboratory') {
        $laboratories = Laboratory::all();
        foreach ($laboratories as $laboratory) {
            $options .= '<option value="'.$laboratory->id.'">'.$laboratory->name.'</option>';
        }
    }

     return '<select name="admin_id" id="admin_id" class="form-control">'.$options.'</select>';;
}

in my route i have this for Ajax

Route::get('get/admin_id', [App\Http\Controllers\UserController::class, 'getAdminId'])->name('get.admin_id');

in my blade template


@extends('layouts.mainlayout')

@section('content')

<section class="content">
	<div class="body_scroll">
		<div class="block-header">
            <div class="container-fluid">
				<div class="row clearfix">
					<div class="col-lg-12 col-md-12 col-sm-12">
                        <div class="card">
							<div class="body">
                                <h2 class="card-inside-title" >User Registration</h2>
                                @if ($errors->any())
                                <div class="alert alert-danger">
                                    <ul>
                                        @foreach ($errors->all() as $error)
                                            <li>{{ $error }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                                @endif
                                <form method="POST" action="{{ route('users.store') }}">
                                     @csrf
       
                                    <div class="form-group">
                                         <label for="name">Name:</label>
			                            <input type="text" class="form-control" placeholder="name" name = "name" />
		                            </div>

                                    <div class="form-group">
                                        <label for="email">Email:</label>
                                        <input type="email" class="form-control" id="email" placeholder="email"name = "email">
                                    </div>

                                    <div class="form-group">
                                         <label for="password">Password:</label>
                                        <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                                     </div>
                                     <div class="form-group ">
                                     <label for="role">Roles:</label>
                                    <select name="roles[]" id="roles" class= "form-control show-tick ms select2" multiple data-placeholder="Select Roles">
                                    @foreach($roles as $tag)
                                        <option value="{{$tag}}"           
                                        >{{$tag}}</option>
                                        @endforeach
                                    </select>
                                </div>

                                     <div class="form-group">
                                        <label for="admin_type">Admin Type</label>
                                        <select name="admin_type" id="admin_type" class="form-control">

                                            <option value="college">College</option>
                                            <option value="department">Department</option>
                                            <option value="laboratory">Laboratory</option>
                                        </select>
                                    </div>

                                     <div class="form-group">
                                    <label for="admin_id">Admin ID</label>
                                    <select name="admin_id" id="admin_id" class="form-control">
                                        <option value="">   </option>
                                    </select>
                                </div>
                                   
                                     <div>
                                     <button class="btn btn-raised btn-primary waves-effect" onclick="this.form.submit()" type="submit">SUBMIT</button>
                                     </div>
                                     
                                 </form>
                            </div>
                        </div>    
                    </div>
                </div>
            </div>
        </div>
    </div>
    
</section>
@endsection
@section('scripts')
<script>
$(document).ready(function(){
    $('#admin_type').on('change', function(){
        var adminType = $(this).val();
        $.ajax({
            type:'GET',
            url: '{{ route('get.admin_id') }}',
            data: { admin_type: adminType },
            success:function(data){
                console.log(data);
                $('#admin_id').append(data);
                

               
                
            }
        });
        
    });
});
</script>




@endsection

and in console l got what i want like this "habtewolddf" but in the blade page the options are not coming, I dont know why it is not working any one who can help me please please???

0 likes
8 replies
tykus's avatar

Take care of your quotation marks; also empty the options because otherwise it will add everytime you change the type:

$.ajax({
   type:'GET',
   url: '{{ route("get.admin_id") }}',
   data: { admin_type: adminType },
   success:function(data){
    console.log(data);
    $('#admin_id').empty().append(data);                
  }
});
1 like
luk's avatar
Level 1

@tykus i also try it but it dose not work still!

tykus's avatar

@luk can you check (i) that there is an outbound Request whenever admin-type is changed, (ii) that the Request goes to the correct URL (iii) that the URL maps to the correct Controller action (iv) that there is a HTML string returned.

Aside, you should not include the select select element in the HTML payload, just the options. Personally I would create a Blade template partial to build up the HTML rather than inline in the PHP - since it will be easier to reason about. For example:

public function getAdminId(Request $request)
{
    $models = match($request->admin_type, {
    	'college' => College::pluck('name', 'id'),
        'department' => Department::pluck('name', 'id'),
        'laboratory' => Laboratory::pluck('name', 'id'),
        default => []
	};

    return view('partials.admin-ids', compact('models'))->render();
}
<option value="">Select an option</option>
@foreach($models as $id => $name)
    <option value="{{ $id }}" {{ old('admin_id') === $id ? 'selected' : '' }}>
        {{ $name }}
    </option>
@endforeach
1 like
luk's avatar
Level 1

@tykus is pass all you asked that is why i show all the optioins in the console and i dont think the problem is that since the values are just here in the Ajax which means the urls also working fine

tykus's avatar

@luk yes, correct

since the values are just here in the Ajax which means the urls also working fine

So the problem is with appending to the select element only? Is this select the only element with that id in the DOM?

1 like
luk's avatar
Level 1

@tykus i don't understand what you want to say? can you explain it please ?

jstn's avatar

Did you check if $request->admin_type has a value in your getAdminId function?

1 like
luk's avatar
Level 1

@jstn yeah i used

if(isset($request->admin_type)) {
    $adminType = $request->admin_type;
    $options = '';

    if ($adminType == 'college') {
        $colleges = College::all();
        foreach ($colleges as $college) {
            $options .= '<option value="'.$college->id.'">'.$college->name.'</option>';
        }
    } elseif ($adminType == 'department') {
        $departments = Department::all();
        foreach ($departments as $department) {
            $options .= '<option value="'.$department->id.'">'.$department->name.'</option>';
        }
    } elseif ($adminType == 'laboratory') {
        $laboratories = Laboratory::all();
        foreach ($laboratories as $laboratory) {
            $options .= '<option value="'.$laboratory->id.'">'.$laboratory->name.'</option>';
        }
    }
    return $options;
} else {
    return 'Select Admin Type First';
}

and in the console i got the correct value as what i expected , the problem is just rendering the data as options in the page

Please or to participate in this conversation.