1

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.

Jaaayz
  • 1,533
  • 7
  • 27
  • 59
  • where is the problem ? is there any error ? –  Mar 27 '18 at 09:55
  • Can you tell me what issue you are having now? – athulpraj Mar 27 '18 at 09:55
  • @HasanTıngır no errors is showed but I would like to populate the second dropdown base on my selection of the service on the first dropdown – Jaaayz Mar 27 '18 at 10:09
  • updated question @HasanTıngır – Jaaayz Mar 27 '18 at 10:15
  • Can you look at error log ? (storage/logs/laravel.log) May we can find more information what causes this error –  Mar 27 '18 at 10:24
  • Also I have to ask is Service is a request instance ? (`getCategories(Service $service)`) You are sending get method, there is no post data so you shouldn't use a request instance. $service parameter coming from url –  Mar 27 '18 at 10:26

1 Answers1

1

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);
SystemGlitch
  • 2,150
  • 12
  • 27
  • I got a 500 internal server error? Is there any changes I would make in my defined route? – Jaaayz Mar 27 '18 at 10:34
  • If you have any, please tell us the exact error. You can get them in `storage/logs/laravel.log`. Your route is ok, you don't need to change it. – SystemGlitch Mar 27 '18 at 10:39
  • I added it but still got the same 500 internal server error. – Jaaayz Mar 27 '18 at 10:50
  • Please tell us the error's detail, otherwise we can't help you. – SystemGlitch Mar 27 '18 at 10:52
  • IS this the one? in the console log {message: "Method select does not exist.", exception: "BadMethodCallException",…} exception : "BadMethodCallException" file : "/home/jayzyaj/Documents/CrisDMS/dms-server/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php" line : 96 message : "Method select does not exist." – Jaaayz Mar 27 '18 at 11:09
  • Oh yes indeed, the selected columns are to be specified in [`get()`](https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_get) : `$service->categories->get(['id','name']);` – SystemGlitch Mar 27 '18 at 11:48
  • Now I got an array_key_exists(): The first argument should be either a string or an integer. – – Jaaayz Mar 28 '18 at 12:40
  • Your new problem seems unrelated, please post another question if you don't find any solution in the already answered ones. – SystemGlitch Mar 28 '18 at 13:53
  • Yesyes. Thanks for helping anyway. Appreciate it alot! – Jaaayz Mar 28 '18 at 14:02
  • I had already figured out on how to get the fields using pluck(). However when I choose the first dropdown it emptys the second dropdown – Jaaayz Mar 29 '18 at 04:09