MegaXLR MegaXLR - 15 days ago 7
PHP Question

Laravel Eloquent where in relationship may or may not have result

I've got this relation:

A

Company
may have one or more
Employees
.

I need to
SELECT
Companies based on the
first_name
of an
Employee
, but not show it when the
first_name
of the employee doesn't match.

This is what I currently have.

$companies = Company::with(array('employees' => function($q) {
$type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
$q->where( 'employees.first_name', 'LIKE', $type);
}))->get();


The employee
first_name
must be neglected if the
Company
doesn't have any
Employee
s

But it shows the Company data, even if the employee doesn't match. the employee just gets hidden.

How would I go on doing this?

Answer

Try that way:

$companies = Company::whereHas('employees', function($q){
    $type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
    $q->where( 'first_name', 'LIKE', $type);
})->get();

or if it doesnt work add 'employees' to where clause:

$q->where('employees.first_name', 'LIKE', $type);
Comments