Ad

Where Should The Logic For Complex Update Validation Live?

I'm having a discussion with my team and utilizing the Laravel framework.

Validating an update to an existing model's attribute that is a relationship requires a few DB calls to make sure it fits in the constraints.

My first thought is to create a custom validator, however, this would require queries within the validator. one to get the model being updated, one to get the relationship that exists and one to get the relationship that it would be updated too. This validator would also only ever be used for updating this one attribute on this one model.

Alternatively, this could be validated via an event, but I'm not sure the best place to keep that validation logic.

Any advice would be deeply appreciated.

Ad

Answer

Laravel's custom validation rules were pretty much made for this

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function ($query) {
            $query->where('account_id', 1);
        }),
    ],
]);

You can put whatever constraints you want one the query, it'll pass as long as at least 1 record is returned

Ad
source: stackoverflow.com
Ad