Laravel Snippet: Auto Trim Fields From Database in Model
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… 😕
/**
* 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 … 😅