Resources

Validations

Validations allows you to check incoming requests to avoid inconstancies in your database.

Keep in mind that if you want your API to provide the best user experience to your consumers you always want to have 0 direct database errors. For example, if one of your fields is not nullable, you'll want to make it required in these rules. You can specify all Laravel rules you want.

Rules

You may use the rules method from your resource to specify the rules for your attributes.

UserResource.php
public function rules(\Lomkit\Rest\Http\Requests\RestRequest $request) {
    return [
        'name' => 'required'
    ];
}

Create rules

You may use the createRules method from your resource to specify the creating rules.

UserResource.php
public function createRules(\Lomkit\Rest\Http\Requests\RestRequest $request) {
    return [
        'name' => 'required'
    ];
}

Update rules

You may use the updateRules method from your resource to specify the updating rules.

UserResource.php
public function updateRules(\Lomkit\Rest\Http\Requests\RestRequest $request) {
    return [
        'name' => 'required'
    ];
}

Relation pivot rules

In some particular cases, you might want to validate the pivot fields provided by the incoming request. You can achieve this with the withPivotRules method when declaring your relationship:

use Lomkit\Rest\Relations\BelongsToMany;

BelongsToMany::make('roles', RoleResource::class)
    ->withPivotFields(['created_at'])
    ->withPivotRules([
        'created_at' => ['required', 'date']
    ]),

Copyright © 2024