Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Getting subsets of validated data in Laravel 8.x

Laravel offers mainly two ways to validate the request data inside of the controller methods. Either you can directly call the validate method on the Illuminate\Http\Request object and set the validation rules or you can create a form request and type-hint the controller method with this form request class.

Here’s how you can validate request data using the first method.

public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|unique:posts',
        'body' => 'required',
    ]);

    // The book data is valid...
}

Now, if you want to retrieve the incoming request data that underwent validation, you can do so by calling the validated method on the request object like so.

$validatedData = $request->validated();

This method returns an array of the data that was validated.

So, what if you want to only retrieve a certain set of validated data? How would you do that?

Well, a recent PR by Taylor Otwell for Laravel 8.x tries to fix this.

Subsets of validated data

Laravel 8.x now comes with a safe method which you can call on a form request or validator instance. This method returns an instance of Illuminate\Support\ValidatedInput.

This object comprises of mainly three methods: only, except, and all.

  • The only method

You can call this method to only retrieve certain validated fields like so.

$validated = $request->safe()->only(['title', 'body']);

In this case, only title and body fields will be retrieved.

  • The except method
$validated = $request->safe()->except(['title', 'body']);

In this case, every validated field except the title and body fields will be retrieved.

  • The all method
$validated = $request->safe()->all();

As its name suggests, this method will retrieve all the validated fields the same way the validated method does.

You can call the safe and all these methods on form requests the same way as the validator instance as well.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?