Is there a way I can trim the original values before Laravel captures them?
Laravel already trims the input. You can verify it by going to \App\Http\Kernel and in $middleware property you should see \App\Http\Middleware\TrimStrings::class.
I am working with an old MS SQL database where nearly all string columns are of type char.
Is there a way I can trim the original values before Laravel captures them?
I have added the following to the Model but this seems to be causing issues with isDirty() flagging all the columns as dirty as they no longer have the whitespace at the end.
/**
* Get a plain attribute (not a relationship).
*
* @param string $key
* @return mixed
*/
public function getAttributeValue($key)
{
$value = parent::getAttributeValue($key);
return is_string($value) ? trim($value) : $value;
}
If anybody else wants to achieve this where they can't control the data entered in to the application or the database column types used then I managed to do it by overriding this method on the model and using trim on the attributes. I am yet to come across any issues.
/**
* Set the array of model attributes. No checking is done.
*
* @param array $attributes
* @param bool $sync
* @return $this
*/
public function setRawAttributes(array $attributes, $sync = false)
{
$this->attributes = collect($attributes)->map(function ($item, $key) {
return is_string($item) ? trim($item) : $item;
})->toArray();
if ($sync) {
$this->syncOriginal();
}
$this->classCastCache = [];
return $this;
}
Please or to participate in this conversation.