Reputation: 1998
Lets say I have a relationship on a model like this
public function currentInvoices($time = 'current'){
switch ($time) {
case 'current':
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
break;
case 'lastMonth':
$start = Carbon::create()->subMonth()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->subMonth()->endOfMonth()->format('Y-m-d H:i:s');
break;
default:
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
}
return $this->hasManyThrough(
'App\Models\Invoices',
'App\Models\Tenancies\Tenancies',
'linked_tenant_id', // Foreign key on Tenancies table...
'tenant_id', // Foreign key on invoices table...
'id', // Local key on tenants table...
'id' // Local key on tenancies table...
)->where('invoices.start_date','>=',$start)->where('invoices.end_date','<=',$end);
}
How would I pass an argument when using eloquents has
. For example, this is what i'm trying to achieve
$tenantCompany = $tenantCompany->has('currentInvoices','lastMonth');
Is it possible to pass a second argument into eloquents has
function? If not any suggestions on how I can achieve this?
Upvotes: 0
Views: 103
Reputation: 8297
I prefer to do it like this
public function invoices(){
return $this->hasManyThrough(
'App\Models\Invoices',
'App\Models\Tenancies\Tenancies',
'linked_tenant_id', // Foreign key on Tenancies table...
'tenant_id', // Foreign key on invoices table...
'id', // Local key on tenants table...
'id' // Local key on tenancies table...
);
}
public function currentInvoices(){
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
return $this->invoices()->where('invoices.start_date','>=',$start)
->where('invoices.end_date','<=',$end);
}
public function lastMonthInvoices(){
$start = Carbon::create()->subMonth()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->subMonth()->endOfMonth()->format('Y-m-d H:i:s');
return $this->invoices()->where('invoices.start_date','>=',$start)
->where('invoices.end_date','<=',$end);
}
Now fetch it like this
$tenantCompany = $tenantCompany->has('lastMonthInvoices');
Upvotes: 0
Reputation: 4026
You can use whereHas
$tenantCompany = $tenantCompany->whereHas('currentInvoices', function($query) use($start_date, $end_date {
$query->where('start_date', '>=', $start_date)->where('end_date', '<=', $end_date);
})->get();
More about relationship methods: https://laravel.com/docs/5.6/eloquent-relationships
Upvotes: 1