mardi 27 mars 2018

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 = '' + $(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();
    }

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

Appreciate if someone could help.

Thanks in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire