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

Gabotronix's avatar

Attach property to Eloquent model

Hi everybody, I was wondering if there's a way to attach an atribute to eloquent collections , like I want to calculate the ritems available from looping through items array.

I know you could make this by looping through each item and increasing the country but how can I automate the proccess for each model instance, so I can make a select input range with $stockLeft.

Here is my controller method:

public function descuentoSlug( $slug )
    {
        $discount = Discount::getBySlug($slug)->toArray();
        
        $stockLeft = 0;

        foreach($discount['discountcodes'] as $code){
            if($code['isBought'] == false){
                $stockLeft++;
            }
        }
        
        $discount['stockLeft'] = $stockLeft;
        
        $meta = 
        [
            'title'      => $discount['title'],
            'description'      => '',
            'breadcumbs' => [ 'Descuentos', $discount['title'] ]
        ];
        
        
        return view('descuentos.show', compact('meta', 'discount'));
    }

How van I attach a computed atribute to Discount Eloquent Model?

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Add an accessor method on the Model class which calculates the $stockLeft property:

// Discount.php

public function getStockLeftAttribute()
{
    return collect($this->discountcodes)->reject(function ($code) {
        return $code->isBought;
    })->count();
}

Please or to participate in this conversation.