Validation is the process of checking whether the submitted data adheres to the defined rules governing the processing of that data. For example, if a user submits an email address, then we expect that email address to be valid. If the @
symbol is missing from the submitted email address, then the submitted value does not adhere to the defined rules of what is acceptable as an email address. If the submitted input meets all the defined rules for an acceptable email address, then it is accepted as a valid email address.
In this tutorial, we will look at various validation types and how we can perform validation using Laravel.
In this tutorial, we will cover the following topics
The following are some of the advantages of data validation
The following are some of the common data validation types
The above list is not exhaustive but lists some of the common rules that we will have to work with in Laravel applications.
Let's create a new project and learn how to validate user input in Laravel.
Run the following command to create a new project
composer create-project laravel/laravel validation 6.0.*
HERE,
We will now create a simple HTML form that simulates user registration on a website. Our form will be will be able to accept the following parameters and validation rules
Let's now create an HTML form that will accept input from the user.
Create a new directory users in /resources/views
Create a new file create.blade.php
in the directory /resources/views/users
Add the following code to create.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{$title}}</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="{{asset('css/style.css')}}" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="table-wrapper">
<div class="table-title">
<div class="row">
<div class="col-sm-6">
<h2>User <b>Registration</b></h2>
</div>
</div>
</div>
<form action="{{route('users.create')}}" method="POST">
@csrf
<div class="form-group {{ $errors->has('username') ? ' has-error' : '' }}">
<label for="username">Username</label>
<input class="form-control" name="username" value="{{Request::old('username')}}" placeholder="Enter username" type="text">
@if ($errors->has('username'))
<span class="help-block">{{ $errors->first('username') }}</span>
@endif
</div>
<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email">Email</label>
<input class="form-control" name="email" value="{{Request::old('email')}}" placeholder="Enter email" type="email">
@if ($errors->has('email'))
<span class="help-block">{{ $errors->first('email') }}</span>
@endif
</div>
<div class="form-group {{ $errors->has('password') ? ' has-error' : '' }}">
<label for="email">Password</label>
<input class="form-control" name="password" placeholder="Enter password" type="password">
@if ($errors->has('password'))
<span class="help-block">{{ $errors->first('password') }}</span>
@endif
</div>
<button class="btn btn-success" type="submit">
<i class="fa fa-save"></i> Register
</button>
</form>
</div>
</div>
</body>
</html>
HERE,
<form action=\"{{route(\'users.create\')}}\" method=\"POST\"\>
opens the form element, sets the action method to the named route users.create and sets the form method to POST\@csrf
sets the CSRF token using a blade directive<input class="form-control" name="username" value="{{Request::old('username')}}" placeholder="Enter username" type="text">
defines the input control for the username name that is also named username. value="{{Request::old('username')}}"
is used to preserve the value that was supplied for the particular input before submitting to the server for validation. For example, if a user enters a valid username but supplies an invalid password, then the previously supplied username will be preserved in the form. Without this, the user will be required to fill in all the input controls again even for fields that passed validation.@if ($errors->has('username'))... @endif
checks if the error array contains any element named username then displays the error message using <span class="help-block">{{ $errors->first('password') }}</span>
if the condition evaluates to true.Let's now create a controller that will respond to our actions
Open the command line / terminal
Run the following command
php artisan make:controller UserController
HERE,
UserController
in app/Http/Controllers
directoryUpdate the controller code to the following
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(){
return 'Congratulations. User account has successfully been created.';
}
public function create(){
$params = [
'title' => 'User Registration',
];
return view('users.create')->with($params);
}
public function store(Request $request){
$request->validate([
'username' => 'required|alpha_dash',
'email' => 'required|email',
'password' => 'required'
]);
return redirect()->route('users.index');
}
}
HERE,
public function index(){...}
defines the index method that outputs simple text in the web browserpublic function create(){...}
defines the create method that displays the user registration form.public function store(Request $request){...}
defines that store method that validates our user input then redirects to the users.index
route. For simplicity's sake, we are not writing the values to the database.Now that we have created our view and controller, let's wrap it up with the routes
Open /routes/web.php
Add the following routes
Route::get('/users',[
'uses' => 'UserController@index',
'as' => 'users.index'
]);
Route::get('/register',[
'uses' => 'UserController@create',
'as' => 'users.create'
]);
Route::post('/register',[
'uses' => 'UserController@store',
]);
HERE,
users.index
, and users.create
. users.create
has two HTTP verbs GET and POST that use the same path.Let's now start our built-in web server to see how our application functions.
Run the following command
php artisan serve
Load the following route into your browser
http://127.0.0.1:8000/register
You should be able to see the following form
Click on Register button
You should be able to see the following errors
Fill in the required details and click on Register
You should be able to see the following simple message if all validation rules pass
Congratulations. User account has successfully been created.
Try to enter valid data for the username then click on register to see what happens.
In this lesson, we covered the basics of Laravel form validation. We also created a simple practical example that shows us how to implement validation in Laravel and display errors to the user. We also learnt how to preserve the user input when validation passes for some fields and fails for others.
If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.
This tutorial shows you how to create an admin panel from scratch using Laravel 5 MVC framework.
© 2014 to 2019 KodeBlog