Jaaayz
Jaaayz

Reputation: 1563

Laravel dynamic dropdown base on hasMany relationships

I'm trying to create a dynamic two dynamic dropdown menus. These are the service and category selection from my database. I need to make the second dropdown menu which is the category that is dependent on the service. When I select [service_code] it will give a different bunch of categories base on the selected service.

Here is the relationship between the two models.

Service.php

public function categories()
        {
            return $this->hasMany('App\Models\Categories', 'service_id', 'id');
        }

Categories.php

public function service()
    {
        return $this->belongsTo('App\Models\Service', 'service_id');
    }

Here is the code in my controller

AnalysisRequestController.php

public function create()
    {
        $client = Client::all()->sortBy('client_name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('client_name', 'id');
        $services = Service::with('categories')->get()->sortBy('code', SORT_NATURAL | SORT_FLAG_CASE)->pluck('description', 'id');
        $categories = Categories::with('service')->get()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');

        return view('encoder-dashboard.analysis-request.create', compact('client', 'services', 'categories'));
    }

Here is the code in my view

fields.blade.php

<!-- Service Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('service_id', 'Service:') !!}
     {!! Form::select('service_id', $services, null, ['class' => 'form-control','required'])!!}
</div>

<!-- Categories Id Field -->
<div class="form-group col-sm-6">
    {!! Form::label('category_id', 'Category:') !!}
     {!! Form::select('category_id', $categories, null, ['class' => 'form-control','required'])!!}
</div>

Here is my script section for the request

<script>
        $(function() {
            $('select[name=service_id]').change(function() {

                var url = '{{ url('service') }}' + $(this).val() + '/categories/';

                $.get(url, function(data) {
                    var select = $('form select[name= category_id]');

                    select.empty();

                    $.each(data,function(key, value) {
                        select.append('<option value=' + value.id + '>' + value.name + '</option>');
                    });
                });
            });
        });
    </script>

Here is the defined route

Route::get('service/{service}/categories', 'ServiceController@getCategories');

And lastly here is the function in the controller

ServiceController.php

public function getCategories(Service $service)
    {
        return $service->categories->select('id', 'name')->get();
    }

when I open the console in my browser I got this error.

GET http://127.0.0.1:8000/service/3/categories/ 404 (Not Found)

I tried to follow the answer in this link but still not working..

Appreciate if someone could help.

Thanks in advance.

Upvotes: 1

Views: 1562

Answers (1)

SystemGlitch
SystemGlitch

Reputation: 2262

The route parameter is an ID, not an object. You have to get your model instance yourself.

So getCategories() should look like this:

public function getCategories($idService)
{
    $service = Service::findOrFail($idService);
    return $service->categories->get(['id','name']);;
}

Edit: To avoid getting an error 500 if the id in the url is not numeric (example: http://127.0.0.1:8000/service/someText/categories/, add a simple check at the beginning of your method:

if(!is_numeric($idService)) abort(404);

Upvotes: 1

Related Questions