Laravel - Validation

Laravel - Validation

Step 1: Create a Controller for Validation

Use the Artisan command to create a ValidationController:

php artisan make:controller ValidationController --plain

Step 2: Add Methods in the Controller

Next, in your app/Http/Controllers/ValidationController.php, add the following methods to show the form and handle form validation:

namespace App\Http\Controllers; use Illuminate\Http\Request; class ValidationController extends Controller { // Show the login form public function showform() { return view('login'); } // Handle form validation public function validateform(Request $request) { // Print all incoming data (for debugging purposes) print_r($request->all()); // Validate the form input $this->validate($request, [ 'username' => 'required|max:8', 'password' => 'required', ]); // Proceed with further logic if validation passes // For example, redirect or process data } }

Step 3: Create a View File for the Form

Create the view file resources/views/login.blade.php and add the following code for the login form:

@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading">Login</div> <div class="panel-body"> <!-- Display validation errors if any --> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <!-- Login form --> <form method="POST" action="{{ url('/validation') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}"> <label for="username">Username</label> <input id="username" type="text" class="form-control" name="username" value="{{ old('username') }}" required> @if ($errors->has('username')) <span class="help-block"> <strong>{{ $errors->first('username') }}</strong> </span> @endif </div> <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}"> <label for="password">Password</label> <input id="password" type="password" class="form-control" name="password" required> @if ($errors->has('password')) <span class="help-block"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> <button type="submit" class="btn btn-primary"> Login </button> </form> </div> </div> </div> </div> </div> @endsection

In this view:

  • The validation errors are displayed if any are present using the $errors variable.

  • The form contains username and password fields, which are validated in the controller.

Step 4: Define Routes

Define the routes for the validation form and POST request in your routes/web.php file:

Route::get('/validation', 'ValidationController@showform'); Route::post('/validation', 'ValidationController@validateform');

Step 5: Test the Validation

Now, visit the following URL in your browser to test the validation:

http://localhost:8000/validation

If you click the "Login" button without entering anything in the fields, you will see error messages like:

  • The username field is required.

  • The password field is required.

This ensures that the form is properly validated before being processed.

Explanation of the Code

  1. Validation Rules:

    • In the validateform method, the validate method is used to validate the form data. Here, 'username' => 'required|max:8' checks that the username is required and has a maximum length of 8 characters, and 'password' => 'required' checks that the password field is required.

  2. Error Handling:

    • The errors are displayed in the form if validation fails. In the view, the errors are accessed via the $errors variable, which is an instance of Illuminate\Support\MessageBag.

  3. Displaying Error Messages:

    • If there are any validation errors for a specific field (like username or password), they are shown below the respective input field.

  4. CSRF Token:

    • Laravel uses CSRF protection, so you need to include {{ csrf_field() }} in your form to prevent cross-site request forgery attacks.

Conclusion

This example demonstrates how to implement simple form validation in Laravel. By using the validate method, you ensure that user input is validated before processing it, improving the security and reliability of your application.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close