TCS
TCS

Reputation: 779

Laravel - how to reach model function with API

Trying to reach my model atrributes with api response.

Here's my Customer.php (model)

class Customer extends Model
{
    public function debt()
    {
        if($this->company_id){
            if($this->company->is_fleet){
                $total = $this->company->fleetOrders->where('status', 1)->sum(function($t){ 
                    return $t->total - $t->discount + $t->vat; 
                });
    
                $receipts = $this->company->allReceipts->whereNull('fleet_id')->sum('price');
                return money_formatter($total-$receipts);
            }

            $vehicles = $this->company->vehicles->whereNotNull('fleet_id')->pluck('id')->toArray();
            $total = $this->company->orders->whereNotIn('vehicle_id', $vehicles)->where('status', 1)->sum(function($t){ 
                return $t->total - $t->discount + $t->vat; 
            });

            $receipts = $this->company->allReceipts->whereNull('fleet_id')->sum('price');
            return money_formatter($total-$receipts);
            
        }

        $vehicles = $this->customerVehicles->whereNotNull('fleet_id')->pluck('id')->toArray();
        $total = $this->customerOrders->where('status', 1)->whereNotIn('vehicle_id', $vehicles)->sum(function($t){ 
            return $t->total - $t->discount + $t->vat; 
        });
        $receipts = $this->customerReceipts->whereNull('fleet_id')->sum('price');
        return money_formatter($total-$receipts);
    }
}

And here's what I'm trying to make. I need to reach my "debt" function from other relation. But couldnt make it in health.

  public function index()
    {
        $d = $this->request->all();
        $parameters = $this->request->query();
        $firm_id = $this->request->user()->firm_id;
        $user = $this->request->user();

        $tires = Order::where('firm_id', $firm_id)
        ->with('customer', 'customer.debt')->get()
....

Upvotes: 0

Views: 95

Answers (1)

Raju Rayhan
Raju Rayhan

Reputation: 101

You don't need customer.debt as it's not a relation actually. This method is available on customer already.

While you are looping through $tires you can access that method by $tire->customer->debt()

You can not just pass this like relation I guess. You have to prepare that data in controller or Resource Collection.

Upvotes: 1

Related Questions