How to use input validation laravel as a function?

by tressie.damore , in category: PHP Frameworks , a year ago

How to use input validation laravel as a function?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , a year ago

@tressie.damore 

In Laravel, input validation is typically done using the validation rules defined in the AppHttpRequests directory. However, if you want to use input validation as a function, you can follow these steps:

  1. Create a new file called ValidationHelper.php in the appHelpers directory (you can create this directory if it does not already exist).
  2. In ValidationHelper.php, define a new function called validateInput that accepts two parameters: the request object and an array of validation rules. This function will perform the validation and return the validation errors if any.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php

namespace AppHelpers;

use IlluminateSupportFacadesValidator;
use IlluminateHttpRequest;

class ValidationHelper
{
    public static function validateInput(Request $request, array $rules)
    {
        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return $validator->errors();
        }

        return null;
    }
}


  1. To use the validateInput function, you need to import the ValidationHelper class and call the function, passing in the request object and the validation rules.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
use AppHelpersValidationHelper;
use IlluminateHttpRequest;

public function someFunction(Request $request)
{
    $rules = [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
        // add more validation rules as needed
    ];

    $errors = ValidationHelper::validateInput($request, $rules);

    if ($errors) {
        // handle validation errors, e.g., redirect back with errors
        return redirect()->back()->withErrors($errors)->withInput();
    }

    // continue processing the data

    // return a response
}


Now, whenever you need to validate input, you can use the validateInput function from the ValidationHelper class. This function will return the validation errors if any, which you can use to handle the errors accordingly.