Laravel-Validierung

Aus Vokabulabor
Version vom 9. November 2023, 17:37 Uhr von Hamatoma (Diskussion | Beiträge) (→‎Links)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Zur Navigation springen Zur Suche springen

Links

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],
]);