# Request validation
You can validate your request directly from the action:
public function store(Request $request)
{
$validate = $request->validate([
'code' => 'required|numeric',
'name' => 'required',
'description' => 'required',
'active' => 'boolean'
]);
if ($validate !== true) {
return $validate;
}
$product = Product::create([
'code' => $request->code,
'name' => $request->name,
'description' => $request->description,
'active' => (boolean)$request->active
]);
return new ProductResource($product);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Request class validation
If you are using a request class, then your validation rules go inside the rules method:
public function rules(): array
{
return [
'code' => 'required|numeric',
'name' => 'required',
'description' => 'required',
'active' => 'boolean'
];
}
2
3
4
5
6
7
8
9
If you can, go for Request classes, since you can also customize validation errors as described here.
# Available validation rules
boolean, email, numeric, required
# boolean
The field under validation must be a boolean.
The field under validation must be a valid email address.
# numeric
The field under validation must be numeric.
# required
The field under validation must be present in the input data and not empty.
# Custom validation rules
Since Tea is fairly new, you can create your own validation rules if needed:
php tea make:rule name=Alpha
<?php
namespace App\Rules;
use Devlob\Validation\Rules\Rule;
class Alpha implements Rule
{
public $key = 'alpha';
public function passes(string $attribute, $value): bool
{
return false;
}
public function message(): string
{
return "The :attribute field.";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Key is used as the validation key:
public function rules(): array
{
return [
'name' => 'alpha'
];
}
2
3
4
5
6
Tea will simply make the first letter of the class name lowercase by using the lcfirst php function.
Some examples will be:
Alpha to alpha
AlphaNumeric to alphaNumeric
Thus, if that is not enough for you, you can always update the key.
In order to apply an alpha validation to the rule above we update the passes method:
public function passes(string $attribute, $value): bool
{
return isset($value) && ctype_alpha($value);
}
2
3
4
And message to:
public function message(): string
{
return "The :attribute field should contain only letters.";
}
2
3
4