etelford / laravel-api-validation
Custom Validation for Laravel API requests
Requires
- php: >=7.0
- illuminate/container: ~5.4
- illuminate/http: ~5.4
- illuminate/support: ~5.4
- illuminate/validation: ~5.4
Requires (Dev)
- orchestra/testbench: ~3.0
- phpunit/phpunit: ~5.0
- symfony/var-dumper: ^3.1
This package is auto-updated.
Last update: 2025-04-29 00:18:17 UTC
README
Lightweight package that allows for creating custom validation rules, mainly to be used as an alternative to Form Requests or inline Validators for API requests.
System Requirements
Laravel 5.4+ and PHP >= 7.0.
Installation
Install through Composer.
composer require etelford/laravel-api-validation
Usage
First, import the HandlesApiRequests
trait (usually in your base controller):
use Etelford\LaravelValidation\HandlesApiRequests;
For custom validation using Laravel's built-in validators, make a validation class:
<?php namespace App\Validation\User; class Store extends \Etelford\LaravelValidation\BaseValidator { public function rules() : array { return ['email' => 'required|email']; } }
Then in your controller method, use the validation you just created:
// UserController.php public function store($request, $id) { $this->validate($request, 'User::Store'); }
By default if validation fails, a ApiValidationException
exception will be thrown.
If you wish to bypass this, you can pass a third argument to the validate()
method:
$validator = $this->validate($request, 'User::Store', $throwOnFailure = false);
From this you, you can get the Validator
instance and access all of Laravel's built in Validation methods:
if ($validator->validator()->passes()) {
return true;
}
return false;
If you need more specialized validation that can't be handled directly by Laravel's Validator, you can create a Custom Rule and chain it to your validation call:
class VerifyMinimum extends \Etelford\LaravelValidation\CustomRule { public function passes() : bool { return $this->amount >= $this->minimum; } public function messageBag() : array { return ['amount' => 'Amount must be at least' . $this->minimum]; } } $customRule = new VerifyMinimum(['amount' => 100000, 'minimum' => 50000]); $validation = $class->validate($request, 'entity::bar')->attachRules($customRule);