(Mutators or Middlewares) What would be the ideal use when converting a string before inserting it into the database?

Asked

Viewed 69 times

1

Which would be more recommended to use when manipulating a string that in this case would be (,) for (.) when inserting a value in the database (Mysql) of decimal type in Laravel?

1 - Using a custom middleware

class convertCommaInDot extends TransformsRequest
{

    protected function transform($key, $value)
    {
        return str_replace(',','.',$value);
    }
}

Calling middleware in the route/web.php file

Route::post('/numeros/add', 'NumeroControlador@store')->name('number.store')
    ->middleware('CommaInDot');

OR

2 - Using the setNumeroAttribute($value) mutator, in this case you do not need to use middleware.

class Numero extends Model
{

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

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

Both generate the same result, that is, I insert in the form a number 1,23 and automatically the value is transformed to 1.23

  • 4

    Mutator is for changing given; middleware is for handling HTTP messages. So, mutator is the answer.

  • Igor out of curiosity this Tranformesrequest is a package?

  • In version 6 there is middleware that takes out text space, for example, so I see so what the best way will depend on because the framework opened a gap ! its version is the 5 or 6 (specifies certinho)

  • @Virgilionovic About Transformsrequest, it is a class that Laravel uses to create Convertemptystringstonull middleware.

  • 1

    @Virgilionovic I use the Laravel 6.

  • Yes I ended up finding ... I think your question can be asked in both ways the Laravel has it, but of course with settings and an appropriate code

  • Thank you for the reply @Andersoncarloswoss , thank you.

  • @Virgilionovic hm, got it, thanks for collaborating bro!!

  • Because so Igor this middleware you can do by routes (verb post,put) where this route has data that will be formatted/validated in its own way. (It’s an initial idea, I’m on the street, but tonight I’ll take a look)

Show 4 more comments

1 answer

2


As I always like to have an idea about what each thing does I decided to make an example, the middleware who inherits from the class Transformsrequest has a global function that runs on the general stack of middleware of the application .

Including that kind of middleware is called in the array global:

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,         
    ];

and that middleware should not be configured in routes because its function as quoted is global.

For your problem, it should not be used, because, it checks every item sent in your request and if it is satisfied the exchange of point for comma, is done in all fields that are part of this rule and this is not good, already weighed have a name with point, example Stack.Overflow it will replace summarily by comma getting Stack, and that’s not what you want, you just need to change where it’s number with comma, so, Transformsrequest should only be used when this change occurs in all values sent in your request, which in current version 6 (until that date) has two Transformsrequest global who are:

In your case it is better to use Eloquent: Mutators as is in your question with a change in your code to check too thousand and leave the original value unchanged, only bring the change when it is redeemed, example:

class Numero extends Model
{
    public function getNumeroAttribute($value)
    {
        return str_replace(['.',',']],['','.'], $value); // mudança aqui.
    }
    public function setNumeroAttribute($value)
    {
        $this->attributes['numero'] = str_replace(',','.', $value);
    }
}

References

  • 1

    Um... so from what I understand, the use of Transformsrequest is only valid for global middleware which is the case with Trimstrings and Convertemptystringstonull, and which in my case would not be interesting, since my goal was to apply on specific routes, and in this case the most recommended would be Mutator. Thank you for the reply

  • is that the TransformsRequest would be for all items of the request, I do not think valid then to exchange monetary values ...

  • @Igorac if it is useful to signal as an answer to your question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.