Add or Modify Laravel Form Request Data Before And After Validation

Mohasin Hossain
2 min readJan 3, 2024

--

Form requests are often used for validation purposes only. They can do a whole lot more. Let’s learn some secret about Laravel Form Request Class.

There are so many things you can do with form request and I’m hopping that you already know some of them or all of them. Let me show you some:

  1. Add or modify request data before validation:

Sometimes we need to modify form input before validation or prepare form input data to validate in my way. Here is an example for you:

public function prepareForValidation()
{
$this->merge([
'email' => strtolower($this->email)
]);
}

public function rules()
{
return [
'email' => ['required', 'email', 'max:50', 'unique:users']
]
}

prepareForValidation method alow us to modify data as we need. This a very basic example but hope you will found relevant for your need.

2. Add or modify request data after validation:

Sometimes we also need to modify data after validation like below.

public function all($keys = null)
{
$allValues = parent::all();

$allValues['name'] = ucwords($this->name)

return $allValues;
}

Once again this very basic example and you can use this when it fit for your needs.

3. Adding additional methods:

Sometimes we may do some staff in controller that is actually related with form request class. In this case we can create method for that kind of staff and call that method from controller like this:

$request->ourMethodName()

Secret tip: Laravel Form Request class created on top of Symphony SymfonyRequest class that means Laravel Form Request class extends Symphony SymfonyRequest class and modify as their own.

Bonus: You must love my most read article : How To Use Single Responsibility Principle in PHP/Laravel
And most GitHub star repo:
https://github.com/mohasinhossain/SOLID-Principles-in-PHP

--

--

Mohasin Hossain
Mohasin Hossain

Written by Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux

No responses yet