Ad

Laravel ValidateForm: Prevent Update When Inactive

- 1 answer

I'm trying to prevent an update in a record when the function isActive returns false.

Foo.php

// My Class

public function isActive() {
    return false;
}

FooForm.php

// My Form

public function validateForm()
{
    $this->validate($this->request, [
        'field_1'      => 'required',
        'field_2'      => 'required',
        'field_3'      => 'required',
        'isActive' => 'boolean:true'
    ]);
}

Expected: Block the update because isActive returns false.

Nowadays: Updating without any problem.

EDIT

isActive can't be database property.

Ad

Answer

You are probably looking to implement a custom validation rule.

There are couple ways of doing it as per the linked documentation. Here's an example using the closure method:

public function validateForm()
{
    $this->validate($this->request, [
        'field_1'      => 'required',
        'field_2'      => 'required',
        'field_3'      => 'required',
        'isActive' => function ($attribute, $value, $fail) {
            if (!$this->isActive()) {
                $fail('isActive is false');
            }
        }
    ]);
}

If you need to chain it with other validation rules you can also put the closure into an array like so:

'isActive' => [
    'required',
    function ($attribute, $value, $fail) {
        if (!$this->isActive()) {
            $fail('isActive is false');
        }
    }]
Ad
source: stackoverflow.com
Ad