How To Use Laravel Validation

10
597
How To Use Laravel Validation

Today you are going to learn laravel validation. Several different approaches used to validate your form. You will learn all of them but validation with the form request method is recommended. Laravel form request method for the validation method provides a convenient way to separate business logic from validation. It improves code readability and manageability. So let’s get started.

I assumed that you installed laravel and you have basic knowledge about laravel. Before digging deeper into validation approaches let’s create basic form. I’m using multiple different input fields, which can be used in real-life examples.

Create form with following code into welcome.blade.php.

/* resources > views > welcome.blade.php */

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Validation</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container mt-5">

    @if($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif

    <form action="{{ route('form.store') }}" method="post" enctype="multipart/form-data">
        @csrf
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" class="form-control">
        </div>
        <div class="form-group">
            <label>Email address</label>
            <input type="email" name="email" class="form-control">
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" class="form-control">
        </div>
        <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" name="password_confirmation" class="form-control">
        </div>
        <div class="form-group">
            <label for="image">Select Image</label>
            <input type="file" class="form-control" name="image">
        </div>
        <div class="form-group">
            Gender :
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="gender" value="male">
                <label class="form-check-label">Male</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" name="gender" value="female">
                <label class="form-check-label">Female</label>
            </div>
        </div>
        <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" name="terms_and_conditions">
            <label class="form-check-label">Terms & Conditions</label>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>

    </form>
</div>
</body>
</html>

Create FormController.php to handle form submission.

php artisan make:controller FormController

Create index and store function in FormController.php

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {

    }
}

Finally, define routes to handle form.

/* routes > web.php */

<?php

Route::get('/', 'FormController@index');
Route::post('form/store', 'FormController@store')->name('form.store');

Now, the form is ready to handle validation. We will validate all fields.

# Approach 1: Creating Simple Validation

Write simple validation logic in store method in FormController.php

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed|min:8',
            'password_confirmation' => 'required|min:8',
            'image' => 'required|image',
            'gender' => 'required',
            'terms_and_conditions' => 'required'
        ]);

        return "Form submitted";
    }
}

Lots of validation rules used to validate forms different fields like required, email, confirmed etc. You can find all available validation rules here.

Try to submit a blank form and you will get validation messages above the form. With passing another array into validate method, you can modify validation messages according to your needs.

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {
        $request->validate(
            [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255',
                'password' => 'required|confirmed|min:8',
                'password_confirmation' => 'required|min:8',
                'image' => 'required|image',
                'gender' => 'required',
                'terms_and_conditions' => 'required'
            ],
            [
                'name.required' => 'Please enter name.',
                'email.required' => 'Please enter email address.',
                'email.email' => 'Please enter valid email address.',
            ]
        );

        return "Form submitted";
    }
}

That was the simplest method of validation.

# Approach 2: Creating Manual Validators

To create manual validator modify FormController.php as below.

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255',
                'password' => 'required|confirmed|min:8',
                'password_confirmation' => 'required|min:8',
                'image' => 'required|image',
                'gender' => 'required',
                'terms_and_conditions' => 'required'
            ],
            [
                'name.required' => 'Please enter name.',
                'email.required' => 'Please enter email address.',
                'email.email' => 'Please enter valid email address.',
            ]
        );

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        return "Form submitted";
    }
}

Both of the above approaches are good but it’s not recommended. Why? Because controllers are used for business logic, then why combine validation and business logic? You can separate validation logic with the next approach called the form request method.

# Approach 3: Validation With Form Request

First of all, clear FormController.php.

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(Request $request)
    {

        return "Form submitted";
    }
}

Use the following command to create form request.

php artisan make:request FormValidationRequest

Above code will create new request in app > Http > Requests folder. This approach used for more complex validations.

Open FormValidationRequest.php and replace below code.

/* app > Http > Requests > FormValidationRequest.php */

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FormValidationRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed|min:8',
            'password_confirmation' => 'required|min:8',
            'image' => 'required|image',
            'gender' => 'required',
            'terms_and_conditions' => 'required'
        ];
    }

    public function messages()
    {
        return [
            'name.required' => 'Please enter name.',
            'email.required' => 'Please enter email address.',
            'email.email' => 'Please enter valid email address.',
        ];
    }
}

You need to set authorize true. Rules method is used for set validation rules to input fields like above approaches. Also, you can set custom validation messages with defining messages method.

Import FormValidationRequest.php into FormController.php and update store method as below.

/* app > Http > Controllers > FormController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\FormValidationRequest;


class FormController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function store(FormValidationRequest $request)
    {
        return "Form submitted";
    }
}

Now, try to validate form again. Isn’t it awesome? Controller has more cleaner, readable and manageable code.

Learn more about Laravel Framework

Previous articleHow To Use Laravel Eager Loading
Next articleHow To Use Laravel Mailtrap To Send Email?
Welcome to the world of web development, where technology and creativity come together to bring ideas to life. My name is Keyur Gadher, and as a web development blogger, I am here to share my knowledge and experience with you. From front-end web development to back-end programming, I will provide you with valuable tips, tricks, and techniques to help you create beautiful and functional websites that are tailored to your specific needs. Whether you're a beginner or a seasoned pro, I am here to help you take your web development skills to the next level. Join me today and let's start coding!

10 COMMENTS

  1. Thank you a lot for providing individuals with an extremely marvellous possiblity to read from here. It’s usually very sweet and as well , jam-packed with a lot of fun for me personally and my office fellow workers to visit your site minimum 3 times a week to read through the fresh stuff you have got. And of course, we’re usually astounded with the attractive tricks you serve. Selected two ideas on this page are in fact the finest we have all had.

  2. I have been exploring for a little bit for any high quality articles or blog posts in this sort of area . Exploring in Yahoo I at last stumbled upon this web site. Studying this information So i¡¦m satisfied to express that I’ve an incredibly good uncanny feeling I found out exactly what I needed. I such a lot certainly will make certain to do not omit this site and provides it a glance on a relentless basis.

  3. Somebody essentially assist to make severely articles I might state. That is the first time I frequented your website page and up to now? I amazed with the analysis you made to create this particular put up extraordinary. Wonderful task!

  4. Hey there. I discovered your web site by the use of Google at the same time as looking for a comparable matter, your site got here up. It seems great. I’ve bookmarked it in my google bookmarks to come back then.

LEAVE A REPLY

Please enter your comment!
Please enter your name here