sander106
sander106

Reputation: 71

Laravel crud decimal change dot to comma in the form

I am making a CRUD application, and in the Registrations table there is a price with a decimal that can be with a dot or a comma.

1: i want a validation for a decimal that it accepts dots and commas. for examlple: (9,50 0,50 0.50 9.50)

2: What i want is because the database stores the prices with dots, i want when i try to edit the record in my application it shows the price but it replaces the dot with a comma.

I think i have to use the str_replace function. But i dont know where to use it. Because in the controller i already use str_replace to save it with a dot in the database. Maybe in the html form with jquery?

Any help would be much appriciated!

Upvotes: 2

Views: 4833

Answers (2)

Dawud Abdul Manan
Dawud Abdul Manan

Reputation: 234

if i get you well.I think number_format function will help you with this problem.

$num = 1999.9;
$formattedNum = number_format($num);
echo $formattedNum;
  // this will return 2,000
$formattedNum = number_format($num, 2);
echo $formattedNum;
  //this will  return 1,999.90

However, in you instance, you can use the follow code

number_format($registration->price,2)

It will return the figure with two decimal places. Hope it helps. You can read more on the following link https://www.w3schools.com/php/func_string_number_format.asp

Upvotes: 1

Arcesilas
Arcesilas

Reputation: 1432

You may have a look at accessors: https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor

Then just define the accessor in your model:

    public function getPriceAttribute($value)
    {
        return str_replace('.', ',', $value);
    }

You may define a mutator to make sure the price is always stored with a dot, even if user uses a comma:

    public function setPriceAttribute($value)
    {
        $this->attributes['price'] = str_replace(',', '.', $value);
    }

Now, each time you display the price with $registration->price it will be displayed with a comma, no matter where you use it (any controller, blade template, whatever).

And when assigning the price a value, if it contains a comma, it will be replaced by a dot, no matter where you set it.

Upvotes: 6

Related Questions