Search code examples
laraveleloquentcalculated-columns

Laravel eloquent how do I include exclude from a query a computed appended field?


I have this code which is running ok:

class Basket extends Model
{
use HasFactory;

...

protected $appends = [
    ...
    'price'
];

....
public function getPriceAttribute($value){
    ... some heavy computing
    return $totalPrice;
}

But what I see is that the computing for the price will be executed e.g. when I call

Basket::all();

which is something I want to avoid

I want it only when I do a Basket::find(id) so per single entry.

I haven't find so far how can I avoid eloquent to skip or not the getPriceAttribute

Any Idea?


Solution

  • Once you have created the accessor, and add the value to the appends property on the model:

    protected $appends = [
        ...
        'price'
    ];
    

    it needs to be appended in the controller like below

    $basket = Basket::find($request->id)->append('price');