gibAlex gibAlex - 5 months ago 15x
PHP Question

Laravel RelationShip( join with where)

i need help on laravel 5(use Eloquent)

I have 2 tables

Model Driver

  • id

  • company

Model DriverOnline

  • id

  • name

  • driver_id

I need seatch result on (commany=1 and help me!


If you want to only fetch Driver based on a condition, you can just do this:

Driver::with('online')->where('company', 1)->get();

If the clause is on the relationship, use with and specify a query on that.

$company = 1;
$drivers = Driver::with(['online' => function($query) use ($company)
    $query->where('company', $company);

See "Eager Load Constraints":

Take note of my use. This allows you to include variables from the scope into your Closure instance.

And be aware, if you use either solution, you must set up a relationship. Consult the link I shared with more information on that.

Edit: As per our conversation.

$drivers = Driver::where('company_id','=',1)
    ->whereHas('driversOnline', function($query) {