Skip to content

Instantly share code, notes, and snippets.

@wdmtech
Last active August 18, 2023 14:55
Show Gist options
  • Save wdmtech/564754b7bc42a8de8f9700d3580cc6b9 to your computer and use it in GitHub Desktop.
Save wdmtech/564754b7bc42a8de8f9700d3580cc6b9 to your computer and use it in GitHub Desktop.
Trim all strings in a Laravel Model before they are saved
public static function boot() {
    parent::boot();

    // Trim all string attributes before they are saved
    static::saving(function($model){
        $attributes = collect($model->getAttributes())->map(function ($attribute) {
            if (is_string($attribute)) {
                return trim($attribute);
            }
            return $attribute;
        });

        $model->forceFill($attributes->toArray());
    });
}
@yabdab
Copy link

yabdab commented Aug 17, 2023

Where is this code placed?

@wdmtech
Copy link
Author

wdmtech commented Aug 18, 2023

@

Probably overrides the boot() method of an Eloquent Model (so try it in one of those), but its been a long time since I wrote that, probably about 5 Laravel versions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment