@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 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 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.