Laravel 8.x Validation Example | All Validation In Laravel

Hey Artisan

In this tutorial we are going to laravel validation example. We will see laravel custom validation error messages. Using this you can validate your form before submit. Laravel form validation before submit is very important for your application. So today i will discuss about all laravel form validation procedure. 

Laravel has quite a few ways you can validate incoming data. Laravel validation is the most important topic to save your server data. validating manually or using the validate() method in the controller. Let’s start with the simpler, and more common, validate().

validation-example-laravel-6

 

Basic usage of controller validation

// routes/web.php
Route::get('recipes/create', 'RecipesController@create');
Route::post('recipes', 'RecipesController@store');

 

app/Http/Controllers/RecipesController.php

   namespace App\Http\Controllers;

    use Illuminate\Http\Request;

    class RecipesController extends Controller
    {

        public function create()
        {
            return view('recipes.create');
        }

        public function store(Request $request)
        {
            $this->validate($request, [
                'title' => 'required|unique:recipes|max:125',
                'body' => 'required'
            ]);
            // Recipe is valid; proceed to save it
        }
    }

 

We only have four lines of code running our validation here, but they’re doing a lot. First, we’re explicitly defining the fields we expect and applying rules (here separatedby the pipe character, |) to each individually.

Next, the validate() method checks the incoming data from the $request (which means it can use $request->all() or $request->input() and determines whether or not it is valid.

If the data is valid, the validate method ends and we can move on with your controller method, saving the data or whatever else. But if the data isn’t valid, it throws a ValidationException. This contains instructions to the router about how to handle this exception.

If the request is Ajax (or if it’s requesting JSON as a response), the exception will create a JSON response containing the validation errors.

 

If not, the exception will return a redirect to the previous page, together with all of the user input and the validation errors—perfect for repopulating a failed form and showing some errors.

 

Read Also : Binding Data to Views Using View Composers in Laravel

 

More on Laravel’s Validation Rules

Additionally, you can validate nested properties. This matters if you use HTML’s array syntax, which allows you to, for example, have multiple “users” on an HTML form, each with an associated name. Here’s how you validate that:

 

$this->validate($request, [
  'user.name' => 'required',
  'user.email' => 'required|email',
]);

 

We don’t have enough space to cover every possible validation rule here, but here are a few of the most common rules and their functions:

Require the field

required; required_if:anotherField,equalToThisValue;
required_unless:anotherField,equalToThisValue

 

Field must contain certain types of character

alpha, alpha_dash, alpha_num, numeric, integer

 

Field must contain certain patterns

email, active_url, ip

 

Dates

after:date, before:date (date can be any valid string that strtotime() can handle)

 

Numbers

between:min,max, min:num, max:num, size:num (size tests against length for strings, value for integers, count for arrays, or size in KB for files)

 

Image dimensions

dimensions:min_width=XXX; can also use and/or combine with max_width,
min_height, max_height, width, height, and ratio

 

Databases

exists:tableName, unique:tableName (expects to look in the same table column
as the field name; see the docs for how to customize)

 

Manual Validation

If you are not working in a controller, or if for some other reason the previously described flow is not a good fit.

 

you can manually create a Validator instance and check for success or failure like below example

  Route::get('recipes/create', function () {
        return view('recipes.create');
    });
    Route::post('recipes', function (Illuminate\Http\Request $request) {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:recipes|max:125',
            'body' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect('recipes/create')
                ->withErrors($validator)
                ->withInput();
        }
        // Recipe is valid; proceed to save it
    });

 

As you can see, we create an instance of a validator by passing it our input as the first parameter and the validation rules as the second parameter.

The validator exposes a fails() method that we can check against and can be passed into the withErrors() method of the redirect.

Displaying Validation Error Messages

The validate() method in controllers (and the withErrors() method on redirects that it relies on) flashes any errors to the session. These errors are made available to the view you’re being redirected to in the $errors variable.

And remember that as a part of Laravel’s magic, that $errors variable will be available every time you load the view, even if it’s just empty, so you don’t have to check if it exists with isset().

Echo validation errors

 

Hope it will help you.

 

#laravel #validation-example #data-validate #data-validation #form-validation #input-validation