Laravel 5.5 Returns the Request Data from the Validator

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:

And here is a copy and paste friendly version:

public function store()
{
    $data = $this->validate(request(), [
        'name' => 'required',
        'price' => 'required|numeric',
        'category_id' => 'numeric|exists:categories',
    ]);

    // $data = request()->only('name', 'price', 'category_id');

    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:

$data = $this->validate(request(), [
    'name' => 'required',
    'price' => 'required|numeric',
    'notRequiredField' => '',
]);

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


Filed in: Laravel 5.5 / Validation


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Laravel Engineer
Remote okay (must already live in USA)
Hawthorne Effect
Senior Software Engineer (Remote - Contract)
Remote
Koodi Systems
PHP Developer
Pittsburgh / Remote
Sequoia Waste Solutions
Software Developer
Eindhoven
Simac IDS
Application Developer Level II (CakePHP / MySql / Vue.js)
Lancaster, PA
Harbor Compliance
FULL STACK LARAVEL DEVELOPER
LONDON - WEST END
AMPERSAND HEATLH
Mid/Senior Laravel Developer - U.S. Only
Kenner, Louisiana
Profit Miner Technologies