While developing the web application we need server side form validations. Laravel does this task beautifully. In this article I'm going to explain how we can do our form validations in Laravel.
We don't need to write the form validations in our Controller code like generally people does.
Here is an example of writing form validation rules in Laravel.
For example here is the form:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<form method="post" action="{{url('register')}}">
{{csrf_field()}}
<div class="form-group has-feedback">
<input type="text" name="name" class="form-control" placeholder="Name" value="{{old('name')}}">
<input type="email" name="email" class="form-control" placeholder="Email" value="{{old('email')}}">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" name="password" class="form-control" placeholder="Password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
</div>
<!-- /.col -->
</div>
</form>
|
When you will submit the form it will go to register route like:
1
|
Route::post('/register','Auth\RegisterController@postRegister');
|
It says the register route has routed to 'postRegister' function which is inside the 'RegisterController'.
Auth/RegisterController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Requests\RegisterRequest;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class RegisterController extends Controller
{
public function getRegister(){
return view('register');
}
public function postRegister(RegisterRequest $request){
try {
$message = trans('messages.error');
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
]);
if (!empty($user)) {
$message = trans('messages.registered');
return redirect('/register')->with('success_msg', $message);
}
} catch (\Exception $e) {
Log::error(__CLASS__ . "::" . __METHOD__ . " " . $e->getMessage() . "on line" . $e->getLine());
}
return redirect('/register')->with('error_msg', $message);
}
}
|
Now if you see here in 'postRegister' we have passed RegisterRequest for the form validation. So we are going to write validation rules inside RegisterRequest.
Only after validation RegisterRequest rules the code of 'postRegister' can execute else if validation fails it return back with validations errors.
I have created a Requests directory inside 'Http'.
Requests/RegisterRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterRequest extends FormRequest {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'name.required' => 'You first name and last name combination is required'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
return true;
}
}
|
Here in this class I have written all the validation rules. We also need to call atuthorize() function and return true for authorizing the Request.
We also can customize our validation errors by overriding the message function.
Like in above code I have done it for required name.
1
2
3
4
5
6
|
public function messages()
{
return [
'name.required' => 'You first name and last name combination is required'
];
}
|
If I don't customize the error it will return like 'Name is required' but because I have customized it so it will return the customized error.
Here are some of the validation rules example in Laravel:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public function rules() {
return [
'name' => 'required',
'email' => 'required|email|unique:users,email', // check email field in users table weather email id already exist or not
'title' => 'required|required|min:2|max:255', // for minimum 2 and maximum 255 characters
'publish_at' => 'nullable|date',
'device_type' => 'required|in:1,2', // can accept device_type either 1 or 2
'device_token' => 'sometimes', // this is if you wanted to declare optional parameter
'old_password' => 'required|min:8'
'new_password' => 'required|min:8|different:old_password', // if wanted to validated that both old and new password should be different
'confirm_password' => 'required|min:8|same:new_password' // if wanted to validated that both new and confirm password should be same
];
}
|
Now if you wanted to print all the returning validation errors to show the user, The below code will help you to print all the validation errors.
1
2
3
4
5
6
7
8
9
10
|
<!-- for validation errors -->
@if(count($errors) > 0)
<div id="error" class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-ban"></i> Error!</h4>
@foreach($errors->all() as $error)
<div class="msg">{{$error}}</div>
@endforeach
</div>
@endif
|