Laravel 5.5 Returns the Request Data from the Validator


May 4th, 2017

Laravel 5.5 Returns the Request Data from the Validator

A new feature coming to Laravel 5.5 is the Validation will now return the request data so you have everything you need.

Joseph Silber tweeted out a great example of it in action:

???? After validation, you naturally want to get the request data. So in @laravelphp 5.5, validate will return the validated data.

❤️ it!

— Joseph Silber (@joseph_silber) May 4, 2017

And here is a copy and paste friendly version:

1public function store()
3 $data = $this->validate(request(), [
4 'name' => 'required',
5 'price' => 'required|numeric',
6 'category_id' => 'numeric|exists:categories',
7 ]);
9 // $data = request()->only('name', 'price', 'category_id');
11 return Product::create($data);

Since this returns the request()->only() you will need to be sure and define all of your fields in the validation, even if they are not required. You can do this by adding the field with an empty rule like this:

1$data = $this->validate(request(), [
2 'name' => 'required',
3 'price' => 'required|numeric',
4 'notRequiredField' => '',

With that, the field will automatically get added to the allowed request data, but not be restricted by any validation rules.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.