Input Trimming & Normalization
Laravel version > 5.4 already has these features included:
For versions < 5.4: make a new middleware with following code:
public function handle($request, Closure $next)
{
foreach ($request->input() as $key => $value) {
if (! $value) {
$request->request->set($key, NULL);
}
}
return $next($request);
}
and assign it to the routes or controller's methods you want it to take place:
Route::post('/route/{id}', [
'middleware' => NewMiddleware::class,
], function (Request $request, $id) {
Model::find($id)->update($request->all());
});
REMEMBER: create(), update(), etc. methods work on fields in $fillable array in your model:
class User extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'contact', ];
}
Or if you want to exclude some fields and include rest, use $guarded array instead:
class User extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = ['details'];
}
If your field is not in the $fillable array in "Model" class, the update() method will not work for that field!!!
Reference: Mass Assignment