Reputation: 343
Given I have a simple join query:
$googleAds = TrackingApi::where("company_id",$companyId)
->leftJoin("googleads",function($join) use ($date){
$join->on("tracking_api.google_id", "googleads.id")
->where("googleads.created", "<=", $date
})
->select(DB::raw('count(googleads.id) as totalAds'))->get();
The data parameter its comming from admin dashboard, but its optional parameter.
Question: how do I go when $date
its not given ?
Clarification: when $date
not given just perform the query normally.
Upvotes: 1
Views: 90
Reputation: 3455
@user320487 answer was right but, You can also pass the 2nd parameter in method instead of using 'use' keyword in closers that would be a more readable & maintainable code.
$googleAds =
TrackingApi::whereCompany_id($companyId)
->leftJoin("googleads", function ($join) use ($date) {
$join->on("tracking_api.google_id", "googleads.id")
->when($date, function ($query, $date) {
return $query->where("googleads.created", "<=", $date);
});
})
->select(DB::raw('count(googleads.id) as totalAds'))
->get();
Upvotes: 0
Reputation: 2275
As alternative:
$googleAds = TrackingApi::where("company_id", $companyId)
->leftJoin("googleads",function($join) use ($date){
$join->on("tracking_api.google_id", "=", "googleads.id");
if (!empty($date))
$join->where("googleads.created", "<=", $date);
});
->select(DB::raw('count(googleads.id) as totalAds'))
->get();
Upvotes: 0
Reputation:
You can use the when
method:
$googleAds = TrackingApi::where("company_id",$companyId)
->leftJoin("googleads",function($join) use ($date){
$join->on("tracking_api.google_id", "googleads.id")
->when($date, function ($query) use ($date) {
return $query->where("googleads.created", "<=", $date
})
})
->select(DB::raw('count(googleads.id) as totalAds'))->get();
Upvotes: 1