Laravel Validation

Laravel Validation

What is Laravel Validation?

Laravel Validation provides an easy way to validate incoming data, and we know that all the application’s incoming data must be validated before they are stored into the database or processed further, so that we can make sure that the output would be error free.

E.g we want to store the user’s password into the user table and want to make sure that the password must be at least 6 characters long, it should include at least one Alpha, special character and digit. We can achieve this by Laravel validation. There are lots of rules provided by the Laravel framework.

Ways to validate data

  1. Using validate method provided by Illuminate\Http\Request
  2. Using make method provided by Illuminate\Support\Facades\Validator
  3. Using validate method provided by Base Controller App\Http\Controllers
  4. Using Illuminate\Foundation\Http\FormRequest

In this post we will use “Illuminate\Support\Facades\Validator” to validate incoming data.

Using Illuminate\Support\Facades\Validator

Suppose we have a store method inside the controller and we want to store a single blog post for the user.

Note: We generally place all the validation logic inside the Controller, however you can write separate classes for the validation using FormRequest or many other ways (listed below). So any logic we write here for the validation means to be inside Controllers.

In this example we will create two route entry in our route file (web.php), one to display post and one is for creating a post. Next we will require one controller to handle request, say PostController and last we will require one blade file that will have our html view.

Create this two routes in web.php 

//To show post form with title, body and hidden auther_id
Route::get('posts', function() {
		return view('post');
})->name("post.form");

//To store submitted post
Route::post('posts','PostController@store')->name("post.store");

Create this blade file post.blade.php in the resource/views

<html>
   
   <head>
      <title>New Post Form</title>
   </head>

   <body>
      <!-- To show all the validation errors –>
      @if (count($errors) > 0)
         <div class = "alert alert-danger">
            <ul>
               @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
               @endforeach
            </ul>
         </div>
      @endif
      
      <form name="new_post" method="post" action="{{route("post.store")}}">
		  {!! csrf_field() !!}
		  <input type="hidden" name="author_id" value="1"/>
		  
		  <table border = '1'>	
			 <tr>
				<td align = 'center' colspan = '2'>New Post</td>
			 </tr>
			 <tr>
				<td>Title</td>
				<td><input type="text" name="title"/></td>
			 </tr>
			 <tr>
				<td>Post Body</td>
				<td><textarea name="body"></textarea></td>
			 </tr>
			 <tr>
				<td align = 'center' colspan = '2'>
					<button type="submit">Save Post</button>
				</td>
			 </tr>
		  </table>
      
      <form>
      
   </body>
</html>

PostController

public function store(Request $request)
{
   $validator = Validator::make([
       'title' => 'required|unique:posts|min:5|max:255',
       'body' => 'required|string|max:1024',
       'auther_id' => 'required|exists:users,id',
   ]);
   
   if ($validator->fails()) {
     return view('post');
   } else {
      //return redirect wherever you want
   }
 
}

Code Explanation

Validator::make method is responsible for validating all the provided rules. It accepts two parameters, one is an array of rules and second is mixed params. We will discuss this later. 

‘title’ => ‘required|unique:posts|min:5|max:255’,

This line indicates the title param must exist inside the incoming HTTP request (required) and it must be unique (unique:posts) in the table posts and table field title. If you don’t explicitly specify the field name it will consider the same field name as a parameter name under the validation. So here the validation will consider the posts table to have one field called title. The title must have at least 5 (min:5) characters and the title must not exceed 255 (max:255) characters. Here we have also validated the request param with table data.

‘body’ => ‘required|string|max:1024’,

This line indicates the body param must exist inside the incoming HTTP request (required) and it must be string and the body of the post must not be more than 1024 characters logn. 

‘auther_id’ => ‘required|exists:users,id’,

This line indicates the auther_id param must exist inside the incoming HTTP request (required) and the author must exist inside our users table. The users, id explicitly specifies the name of the id field inside the users table.

We have stored validation into the variable $validator so using this variable we are going to check if validation failed or not, if failed we will serve the same view with validation error messages.

Provide a custom message on validation failed.

Everything is clear so far, But, what if you want to customize the error messages provided by Laravel?

This is done by passing array of custom messages as second parameter to Validator::make() method.

public function store(Request $request)
{
   $validator = Validator::make([
       'title' => 'required|unique:posts|min:5|max:255',
       'body' => 'required|string|max:1024',
       'auther_id' => 'required|exists:users,id',
   ], [
       'title.required' => 'Title is required',
       'title.uniqueue' => 'Title already exist',
       'title.min' => 'Title => At least 5 characters required',
       'title.max' => 'Title => Maximum 255 allowed',
       'body.required' => 'Body is required',
       'body.max' => 'Maximum 1024 characters allowed',
       'auther_id.required' => 'Author is required',
       'auther_id.exists' => 'Author not registered',
   ]);

   if ($validator->fails()) {
     return view('post');
   } else {
      //return redirect wherever you want
   }
}

In this post we have seen how we can use laravel’s built-in validation rules, but we can create our one rules as well, for that you can visit our post on custom Laravel Validation.

Bonus Points:

Laravel provides many conditional validation like Required If, Accepted IfDeclined If, Exclude If, Prohibited If. Let’s take an example of Required If.

Required If: The field under validation must be present and not empty if the other field is equal to the given value.

[     
   'list_type'  => 'required',
   'sale_price' => 'required_if:list_type,==,For Sale',
   'rent_price' => 'required_if:list_type,==,For Rent'
]

* sale_price param must be present and not empty if the list_type value is equal to “For Sale”

* rent_price param must be present and not empty if the list_type value is equal to “For Rent”

For more validation rules please visit Laravel official documents.

0 0 votes
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments