Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change field/attribute value in model - Laravel

Tags:

php

laravel

I have the table products with price column. In model I would like to do something like this:

public function getPriceAttribute()
{
    return number_format($this->price);
}

So in view I use

{{ $property->price }} €

and get the value 200 instead 200.00 how is decimal from database.

Is this possible?

like image 215
Sebastian Corneliu Vîrlan Avatar asked Feb 03 '16 18:02

Sebastian Corneliu Vîrlan


2 Answers

This is what solved my problem:

public function getPriceAttribute()
{
    return number_format($this->attributes['price']);
}

This will overwrite the $property->price value (as per comments)

like image 125
Sebastian Corneliu Vîrlan Avatar answered Nov 10 '22 08:11

Sebastian Corneliu Vîrlan


You can do so by passing original value as argument, like this:

public function getPriceAttribute($price)
{
   return number_format($price);
}

You can find more about Mutators (and Casting) here: https://laravel.com/docs/8.x/eloquent-mutators

like image 26
Mihi Avatar answered Nov 10 '22 09:11

Mihi