AbingPj
AbingPj

Reputation: 659

Laravel Eloquent: How to add where condition from the with function model relation

Anyone can help me? How to add where condition from the with function model relation.

I tried ->where('driver.group_id',$group_id) but it does not work. please look my code below.

public function getDriversDailyEarnings()
    {
        $group_id = Auth::user()->group->id;
        $today = Carbon::today();

        $data = DailyEarnings::with(['payout_cost',
        'status:id,name',
        'driver' => function ($query) {
            $query->with('user');
        }])
        ->where('driver.group_id',$group_id)
        ->whereDate('created_at', $today)
        ->get();

        return response()->json($data, 200);
    }

Upvotes: 2

Views: 5392

Answers (3)

Aslam H
Aslam H

Reputation: 1801

You can try this. Haven't tested it yet.

DailyEarnings::with([
      'payout_cost', 
      'status:id,name'
      'driver' => function($query) {
         $query->where('group_id', auth()->user()->group->id)->with('user');
      }
   ])
   ->whereHas('driver', function($query) {
      $query->where('group_id', auth()->user()->group->id);
   })
   ->whereDate('created_at', now()->format('Y-m-d'))
   ->get();

Upvotes: 2

zjbarg
zjbarg

Reputation: 679

Perhaps something like this:

  //        ->where('driver.group_id',$group_id)
            ->whereHas('driver', fn($qry) => $qry->where('group_id', $group_id)) // if group_id a field on driver

Upvotes: 1

Igor Ribeiro
Igor Ribeiro

Reputation: 57

To pass other clauses to a relation, just use it inside an array, where the key and the name of the relation and the value is a function that receives an instance of the query, something like this:

public function getDriversDailyEarnings()
{
    $data = DailyEarnings::with([
        'payout_cost' => function ($myWithQuery) {
            $myWithQuery->where('column-of-relation-here', 'value-here')
                ->orWhere('name', 'LIKE', '%Steve%');;
         }
    ])->get();

    return response()->json($data, 200);
}

Upvotes: 1

Related Questions