Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Chris1989's avatar

Laravel Eloquent query

Hi, Im trying to make an statment to make my calculation inside in a query

Service::query()->where('services.customer_id', '=',$this->custname)->join('payment_invoices', 'payment_invoices.customer_id', '=', 'services.customer_id')
if (payment_invoices::where('id', $this->custname)->exists()) {
   ->sum('payment_invoices.total_cost');
}
else
{
->sum('services.cost');
}

I know that the syntax is wrong but i want an condition inside sql query that if has payment_invoices.total_cost then the sum wil be sum(payment_invoices.total_cost) else the sum will be sum('services.cost') i want the total sum that query but with excact that filter

0 likes
4 replies
Sabonzy's avatar

try assigning the query to a variable first and then chain it up in the conditions

$service =Service::query()
->where('services.customer_id', '=',$this->custname)
->join('payment_invoices', 'payment_invoices.customer_id', '=', 'services.customer_id');

if (payment_invoices::where('id', $this->custname)->exists()) {
  	$service->sum('payment_invoices.total_cost');
}else
{
    $service->sum('services.cost');
}
1 like
Chris1989's avatar

@Sabonzy I tried something like that but maybe must export only one Sum of that something like that sum(services.cost,payment_invoices.total_cost) as total_credits Because i try it and i get error : htmlspecialchars() expects parameter 1 to be string, object given (View: C:\laragon\www\projects\laravel\crm\resources\views\livewire\services\showall.blade.php)

also if make dd i get https://prnt.sc/0ZLtq2wRZu7U

the code that i have now is :

     $this->total_cost =   $service =Service::query()
                ->where('services.customer_id', '=',$this->custname)
                ->join('payment_invoices', 'payment_invoices.customer_id', '=', 'services.customer_id');

                if (PaymentInvoice::where('total_cost')->exists()) {
                $service->sum('payment_invoices.total_cost');
                }else
                {
                $service->sum('services.cost');
                }
Sabonzy's avatar

@Chris1989 you need to call get on the query builder to get the results from the DB. ie $service->get()

MohamedTammam's avatar
$query = Service::query()->where('services.customer_id', '=',$this->custname)->join('payment_invoices', 'payment_invoices.customer_id', '=', 'services.customer_id')
if (payment_invoices::where('id', $this->custname)->exists()) {
  $query->sum('payment_invoices.total_cost');
}
else
{
$query->sum('services.cost');
}
$this->total_cost = $query->get();

Please or to participate in this conversation.