Search code examples
ajaxlaravellaravel-6http-status-code-500wherehas

Laravel6 WhereHas Error 500 when using AJAX


im new to Laravel and facing an interesting Issue right now in my App. I have 3 tables.

Producers

  • id
  • producer_name

Types

  • id
  • type_name

Models

  • id
  • model_name
  • device_type_id
  • device_producer_id

Within my Producers Model I have defined the follwing Filter method:

public function scopeFilterByType($query, $type_id)
{
  $query->whereHas('models', function($q) use $type_id { $q->where('device_type_id', $type_id );});
}

Using Tinker I can do the following:

App\DeviceProducer::filterByType(3)->get()

And get full response with my Producers associated to my given type.

I created an Function so when a user select a device type Ajax will load all Producers from this type.

public function reqProducer(Request $request)
{
  $producers = DeviceProducer::filterByType($request->type_id)->get();
  return response()->json( $producers );
}

But when AJAX is calling my endpoint it gets HTTP500 error.

I figured out when using a request without WhereHas for example:

$producers = DeviceProducer::where('id', $request->producer_id)->get();

It just works fine and I get my results. So it seems have to do something with "WhereHas". I know I could Solve this by first asking Models Table and the creating an Foreach loop. But I this solution would be less readable then my first attempt.

Does anyone has an suggestion what im doing wrong or is it just like there is noch AJAX support for WhereHas querys?

Kind regards Mike


Solution

  • I think this is your issue use $type_id

    Please fix as

    public function scopeFilterByType($query, $type_id)
    {
      $query->whereHas('models', function($q) use ($type_id) { $q->where('device_type_id', $type_id );});
    }