Laravel: Add or Modify Request Data Before Validation

Sometimes you need to add data to the Request or modify it before the validation. Laravel has a few "tricks" for it, with the merge() method.


Option 1. Merge Data in Controller

We can use the merge() method to add data. This method merges an array of data with the Request data. Let's see an example.

Controller:

public function store(Request $request)
{
$request->merge([
'user_id' => auth()->id(),
]);
 
$this->validate($request, [
'user_id' => 'required|exists:users,id',
// ...
]);
}

Option 2. Form Request: prepareForValidation

If you need to modify your Request before validating (for example, separate a field like this user-1 into user and 1), you can use the prepareForValidation method, which is called before the validation is performed.

FormRequest Class:

public function rules(): array
{
return [
'name' => ['required'],
'email' => ['required', 'email', 'max:254'],
'password' => ['required'],
'role' => ['int', 'required'],
];
}
 
protected function prepareForValidation()
{
$this->merge([
// We are exploding the role field from `role-1` to `role` and `1`
'role' => (int)explode('-', $this->role)[1],
// Transforming the name to have the first letter of each word capitalized
'name' => ucwords($this->name),
]);
}

Once submitted, we can look at what $request->validated() gives us:

This method will transform your Request data into a different format, so be careful when directly saving your Request data into the database with $request->validated().

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1057 lessons, total 42 h 44 min)
  • 79 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials