Laravel Snippet: Auto Trim Fields From Database in Model

Filipe Pires
Nerd For Tech
Published in
1 min readJan 5, 2023

This is a quick snippet of code that you insert in your model if you need to automatically trim the values from all model fields using the hydrate method, provided by the Illuminate\Database\Eloquent\Model .

I needed this when working with an ERP that fills all the varchar field lengths with spaces. Weird Stuff indeed… 😕

Pretty Code Snippet (down you can copy-paste version)
    /**
* Auto Trim Field From Database
*
* @return Collection
*/
public function hydrate(array $objects): Collection
{
return parent::hydrate(
array_map(function ($object) {
foreach ($object as $k => $v) {
if (is_string($v)) {
$object->$k = trim($v);
}
}

return $object;
}, $objects)
);
}

In this case, you need to include this code in every Model that needs to auto-trim the fields.

But if you have a situation that every Model or several Models must have this behaviour, then I recommend extending the Model by doing these steps :

  • Create a base class like app/Models/TrimModel.php
  • Define the above hydrate method in the class.
  • Make your model's classes extend the TrimModel class instead of the default Model class.

Happy Codding … 😅

--

--

Filipe Pires
Nerd For Tech

Dad, Senior Software Engineer, Game Dev & Collector, Electronic Prototyping & much more. Passionate about building the future with code.