I connect to a legacy database using Laravel ( Eloquent Models).
String properties of my models are filled with blanks. (due to data inside of the database)
Current output (as JSON for readability) looks like this :
{
"THIRDNAME": "Company ",
"THIRDNAME2": "",
"THIRDADDR": "Street Of Company 117/1 ",
"THIRDADDR2": "",
"THIRDZIP": "1740 ",
"THIRDCITY": "TERNAT "
}
I cannot change that database (other legacy tools using it) but I would like to alter those properties when I query the database. (using Eloquent models)
To get something like this :
{
"THIRDNAME": "Company",
"THIRDNAME2": "",
"THIRDADDR": "Street Of Company 117/1",
"THIRDADDR2": "",
"THIRDZIP": "1740",
"THIRDCITY": "TERNAT"
}
Laravel documentation mentions "Mutators & Casting" but it requires to give specific fields to cast.
I would like to apply a custom "cast" or "mutator" (basic TRIM operation) to all string properties of all models.
How would you achieve this in Laravel ?
Thanks
CodePudding user response:
Model specific, you can override the hydrate() method:
class MyModel extends Model
{
use HasFactory;
protected $fillable = [
// ... //
];
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)
);
}
}
If you want to apply this to all your models, you can extend Model with an abstract class, override hydrate there and have that serve as your base model.
This works because Illuminate\Database\Eloquent\Builder
evokes that method on columns that have been retrieved from the db.
Remember to remove the method return signature if you're using an older PHP version.