How To Validate An Array Of Form Fields With Laravel

People who have used Laravel’s form validation system know how powerful it can be. The problematic and tedious task of validation regarding Laravel becomes very simple and still keeps the door open for complex rules. Here is an easy way of validating a form in Laravel that contains dynamic fields. Larval provides a number of different approaches to validate an applications incoming data. By default, Laravel has a base controller class that uses a ValidateRequests trait that provides a very convenient method to validate various incoming HTTP request within a variety of powerful validation rules.

laravel-request-validation

Validation in depth

What will make the controller method free of all conditional statements and explicit calls to a form request?

Laravel handles the request in a unique manner. There is a specific listener in the FormRequestServiceProvider in which goes through the validation before we even hit the controller. The implementation details are not that important but it is necessary step. It helps us to understand where the application will never give the controller method if the validation fails in anyway. In case that does happen Laravel by default directs the request back to the failed form with populated $errors variables.

A very common use case for such type of forms is when you would allow a user to add more fields to a single form.

When you click the Add New button, it will load a new input field that with field name in complete array. Al of this happens with JavaScript. Below is a quick PHP mockup of the view for form fields:

<input type=”text” class=”form-control” name=”name” value=”name”>

@for ($i=0; $i < 2; $i++)

<input type=”text” name=”items[{{ $i }}]” value=”{{ $i }}”>

@endfor

Laravel gives us a few options when handling an actual validation. The validation makes facade, controller validation and the new form requests. In the next part of this tutorial, we well go through the new form request feature. This same line of code can be applied to both the other options.

Creating a new form request

When you are creating a Form Request Class we can utilize Artisan to have the system automatically generate the file. After opening the terminal, add the cd in your directory and run:

1-zUbLD3eLtFGQSx-lyMdx-Q

$ php artisan make:request OrderRequest

Request created successfully.

After that when you open a new file at app/Http/Requests/OrderRequest.php. You will see this content:

<?php namespace AppHttpRequests;

use AppHttpRequestsRequest;

class OrderRequest extends Request {

public function authorize()

{

return false;

}

public function rules()

{

return [

//

];

}

}

Adjust the Authorize

The first step of the process if to modify the authorize () method. This method will allow you to restrict access by returning true or false. For instance, you could check a user group or any other form of access and then deny it is the access wasn’t a part of the group. For that, you will need to return true to bypass any checks:

public function authorize()

{

return true;

}

Adding custom validation rules

When going through the same file you will notice that the next method is rules and this where you will have to define a custom validation rules. You will be able to find a complete list of rules via official documentation. There are cases where you can keep it simple and force the name field to be required and then each book title the user willing to purchase must be less than 10 characters in length.  You are welcome to using any logic you would like in the rules() method AS long as you return an array.

To handle the dynamic fields you must loop through all the poster items and thinned a rule to each. Below is an updated method for demonstrating this:

public function rules()

{

$rules = [

‘name’ => ‘required|max:255’,

];

 

foreach($this->request->get(‘items’) as $key => $val)

{

$rules[‘items.’.$key] = ‘required|max:10’;

}

 

return $rules;

}

We have to set the first setting the required field name and then loop through all of the $_POST items which will set dynamically the validation for each one. The most important area which to take notice is the array key, Laravel allows you to use the dotted syntax for each item. For instance $riles [‘items.1’] will goa nd straight map to:

<input name=”items[1]”

This can be easy to miss us pay close attention to it, but even now when you submit the form in the browser you will be getting an error message which reads that “items.0”. Do not get confused as Laravel also gives you a fix to this through a message method that allows you to set any custom message that will be returned to the user.

Form request validation message

For fixing this issue, you will have to add a custom message to each of the items. Exactly like the rules() we loop through the items and specifically target the max rule which displays a custom message removing the “items.0”.

1-6RMMblcOXHfX8Yx1Tnw-ww

Conclusion

Form requests are one of the best features of Laravel; there are a few benefits to using this approach which include a standard way of validating requests. Since rules is a standard method you can easily put a custom logic in there for example not hard coding a table name and keeping it simple. You will have a simple object oriented way of organizing the validations. In some of the cases there are different validation rules for storing and updating methods and if you have a separate form request then that is the best way of solving it. Larval is without a doubt one of the best ways through which you can validate a number of form fields without ever worrying about messing up the forms. The simple method and the structure provide you with a great learning curve which is great for newbies and professionals alike.The Laravel application development company get succeeded in delivering amazingly seamless web projects to their clients. Whether it is a big project or a highly complex one, the Laravel developers know how to justify with the expectations of their clients.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s