Laravel-Validierung
Zur Navigation springen
Zur Suche springen
Links
- Laravel
- https://laravel.com/docs/10.x/validation
- https://laravel.com/docs/10.x/validation#custom-validation-rules
https://laravel.com/docs/10.x/validation#available-validation-rules
Wo
In jedem Controller sollte es die Funktion rules() geben, die die Regeln festlegt:
private function rules(): array { return ['scope' => 'required|alpha', 'name' => 'required']; }
Regeln
Regel mittels Closure
use Illuminate\Support\Facades\Validator; use Closure; $validator = Validator::make($request->all(), [ 'title' => ['required', 'max:255', function (string $attribute, mixed $value, Closure $fail) { if ($value === 'foo') { $fail("The {$attribute} is invalid."); } }, ], ]);
Regel erstellen
php artisan make:rule Uppercase
- App/Rules/Uppercase.php
namespace App\Rules; use Closure; use Illuminate\Contracts\Validation\ValidationRule; class Uppercase implements ValidationRule{ public function validate(string $attribute, mixed $value, Closure $fail): void { if (strtoupper($value) !== $value) { $fail('The :attribute must be uppercase.'); } } }
- Benutzung
use App\Rules\Uppercase; $request->validate([ 'name' => ['required', 'string', new Uppercase], ]);