I am trying to sum amount up all cash_sales_items that belong to particular cash_sale using scope in laravel. The problem is when i have some information in those tables the code works fine but when the tables are empty i get an error
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
below is the code and table structures
accessories_cash_salesmysql> describe accessories_cash_sales;
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| client | varchar(255) | NO | | | |
| exchange_rate | int(11) | NO | | 0 | |
| employee_id | int(10) unsigned | NO | MUL | NULL | |
| status | varchar(255) | NO | | | |
| tax | varchar(255) | NO | | | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+---------------+------------------+------+-----+---------+----------------+
and the other is
mysql> describe accessories_cash_sales_items;
+--------------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| accessories_id | int(10) unsigned | NO | MUL | NULL | |
| quantity | int(11) | NO | | 0 | |
| amount | int(11) | NO | | 0 | |
| accessories_cash_sale_id | int(10) unsigned | NO | MUL | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
+--------------------------+------------------+------+-----+---------+----------------+
Am calling the scope method in the blade template with
\App\AccessoriesCashSale::paidOrCollected()
and in the cash sale model paidOrCollected function looks like
public function scopePaidOrCollected($query){
$amount = 0;
$items = $query->where('status', '=', 'paid')->orWhere('status', '=', 'Collected')->whereMonth('created_at','=', date('m'))->get();
foreach($items as $item){
$amount = $amount + $item->accessoriesCashSalesItems()->sum('amount');;
}
return $amount;
}