Skip to content
Advertisement

Laravel scope method check in other table?

I have 3 models, Customer, Service and ServiceElement

My scope in model Customer:

public function scopeServicesExternal($query, $customer_id, $service_id){
        return $query->where('customer_id', $customer_id)->where('service_id', $service_id);
}

This scope gives me all results for a service, this is ok. but it is possible to extend it to get only elements which field agent is not empty in model ServiceElement?

Advertisement

Answer

If the server has a relationship defined to the service element, then you can do:

->whereHas('serviceElement', function($query) {
    return $query->where('field_agent', '!=', '');
});

Which will return only models that have a record for serviceElement and where the field_agent column is not empty.

Replace serviceElement with however you defined the relationship in your model file.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement