Laravel Eloquent: with request parameters

I finally figured out how to put together a complex query to get related models.

This is what my request looks like ...

    $campaign = Campaign::find($campaign_id);
    $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q){
        $q->where('campaign_id', '13');
    }])->get();

In the component part, I am trying to get records from emailsthat have both matching buyer_idand campaign_id. This query achieves exactly what I am doing in a rather efficient way ...

BUT ... I can’t decide how to pass parameters to closure with. At the moment, I have hardcoded the id 13in the request wherein close, but I want it to be equal to $campaign_idthat passed to the original function.

How to do it?

+4
source share
3 answers

, - ... use

    $campaign = Campaign::find($campaign_id);
    $buyers = $campaign->buyers()->with('notes')->with(['emails' => function($q) use ($campaign_id){
        $q->where('campaign_id', $campaign_id);
    }])->get();

?

+9

TRY

$mainQuery=StockTransactionLog::with(['supplier','customer','warehouse','stockInDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_in_details.product_id',$productId);
        },'stockOutDetails'=>function($query) use ($productId){
            $query->with(['product'])->where('product_stock_out_details.product_id',$productId);
        },'stockDamage'=>function($query) use ($productId){
            $query->with(['product'])->where('product_damage_details.product_id',$productId);
        },'stockReturn'=>function($query) use ($productId){
            $query->select('id','return_id','product_id');
            $query->with(['product'])->where('product_return_details.product_id',$productId);
        }]);
+1
$latitude = $request->input('latitude', '44.4562319000');
$longitude = $request->input('longitude', '26.1003480000');
$radius = 1000000;

$locations = Locations::selectRaw("id, name, address, latitude, longitude, image_path, rating, city_id, created_at, active,
                     ( 6371 * acos( cos( radians(?) ) *
                       cos( radians( latitude ) )
                       * cos( radians( longitude ) - radians(?)
                       ) + sin( radians(?) ) *
                       sin( radians( latitude ) ) )
                     ) AS distance", [$latitude, $longitude, $latitude])
    ->where('active', '1')
    ->having("distance", "<", $radius)
    ->orderBy("distance")
    ->get();
0
source

All Articles