Laravel - Validation
Validation is the most important aspect while designing an application. It validates the incoming data. As a matter of course, the base controller class utilizes a ValidatesRequests characteristic which gives an advantageous strategy to approve approaching HTTP demands with an assortment of ground-breaking validation rules.
Available Validation Rules in Laravel
Laravel will dependably check for errors in the session information, and naturally tie them to the view on the off chance that they are accessible. In this way, note a $errors variable will dependably be accessible in the majority of your perspectives on each solicitation, enabling you to helpfully accept the $errors variable is constantly characterized and can be securely utilized. The following table demonstrates all accessible validation runs in Laravel.
The $errors variable will be an instance of Illuminate\Support\MessageBag. The error message can be displayed in the view file by adding the code as shown below.
@if (count($errors) > 0)
<div class = "alert alert-danger">
@foreach ($errors->all() as $error)
{{ $error }}li>
@endforeach
ul>
div>
@endif
Example
Step 1 − Create a controller called ValidationController by executing the following command.
php artisan make:controller ValidationController --plain
Step 2 − After successful execution, you will receive the following output −
Step 3 − Copy the following code in
app/Http/Controllers/ValidationController.php file.
app/Http/Controllers/ValidationController.php
php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ValidationController extends Controller {
public function showform() {
return view('login');
}
public function validateform(Request $request) {
print_r($request->all());
$this->validate($request,[
'username'=>'required|max:8',
'password'=>'required'
]);
}
}
Step 4 − Create a view file called resources/views/login.blade.php and copy the following code in that file.
resources/views/login.blade.php
@if (count($errors) > 0)
class = "alert alert-danger">
@foreach ($errors->all() as $error)
- {{ $error }}
@endforeach
@endif
php
echo Form::open(array('url'=>'/validation'));
?>
border = '1'>
align = 'center' colspan = '2'>Login
Username
php echo Form::text('username'); ?>
Password
php echo Form::password('password'); ?>
align = 'center' colspan = '2'
>php echo Form::submit('Login'); ? >td>
tr>
table>
php
echo Form::close();
?>
Step 5 − Add the following lines in app/Http/routes.php.
app/Http/routes.php
Route::get('/validation','ValidationController@showform');
Route::post('/validation','ValidationController@validateform');
Step 6 − Visit the following URL to test the validation.
http://localhost:8000/validation
Step 7 − Click the “Login” button without entering anything in the text field. The output will be as shown in the following image.
0 Comments
CAN FEEDBACK
Emoji