How to Add Values to the Form Request After Validation in Laravel

Categorized as Laravel

Sometimes it’s necessary to add more values to the form request after it has been validated. These values get returned in this method even though they were not part of the request.

For this, we can use the method validated() in our form request and merge the original request data with our custom data. In the example below, we populate it with the current logged-in user.

In other words, use it when you want to attach additional fields to form request body, e.g., authenticated user id.

We’re not using request()->merge() because it violates the Single Responsibility Principle.

class UpdateBookRequest extends FormRequest 
	public function validated() {
		return array_merge(parent::validated(), ['user_id' => Auth::id()]);

via @shahghasi_adil

Leave a reply

Your email address will not be published. Required fields are marked *