timgavin's avatar

Accessors, but not really

I have several columns on a model dealing with pricing. I want to have a clean way of formatting and printing the price in the view, so I've been messing around with custom methods, like so...

model

$protected $fillable = [
    'my_price'
];

public function myPrice()
{
    return '$' . $this->my_price / 100;
}

view

@if ($user->my_price > 100)
    My Price is {{ $user->myPrice() }}
@endif

I remember something about when accessing a value you could inadvertently query the DB, but if I remember correctly it's doing something like $user->my_price() instead of $user->myPrice() but I wanted to verify I remember this correctly.

I didn't define this as an accessor because I wanted to get the raw value with $user->my_price wherever it's used.

Do you see any issues with this?

0 likes
7 replies
LaryAI's avatar
Level 58

Yes, you're correct. When you use $user->my_price(), Laravel will treat it as a relationship query. If you want to use a method to format your price, you should use $user->myPrice(). However, in your case, I would suggest using an accessor instead.

An accessor in Laravel allows you to format Eloquent attribute values when you access them on your models. Here's how you can define an accessor for your my_price attribute:

public function getMyPriceAttribute($value)
{
    return '$' . $value / 100;
}

Now, you can access the formatted price like this:

echo $user->my_price;

This will automatically call the getMyPriceAttribute method and return the formatted price.

Remember, when defining an accessor, the get prefix is followed by the StudlyCase version of the column name. Also, Laravel will automatically call the accessor, so there's no need to add parentheses () when accessing it.

This way, you can keep your view clean and all the formatting logic in your model.

2 likes
Snapey's avatar
Snapey
Best Answer
Level 122

use an accessor but with a different name

1 like
timgavin's avatar

@Snapey Interesting idea. Is there a benefit to doing that as opposed to what I'm doing?

1 like
PovilasKorop's avatar

@timgavin the benefit is that you could put that logic INSIDE of the accessor.

Instead of:

@if ($user->my_price > 100)
    My Price is {{ $user->myPrice() }}
@endif

You would do:

{{ $user->my_formatted_price }}

And in the Model:

public function getMyFormattedPrice() {
    if ($this->my_price > 100) {
        return 'My Price is $ ' . $value / 100;
    } else {
        return $this->my_price;
    }
}
2 likes
timgavin's avatar

@PovilasKorop Thanks Povilas, this was just an example as to the situations I may encounter, but it's a good tip!

1 like
Snapey's avatar

and also look into number_format() php function or NumberFormatter class

1 like

Please or to participate in this conversation.