Friendly Code
Friendly Code

Reputation: 1645

Laravel Validation Rule - At least one input value change must be made

I have a model with title, subtitle, date and am building a form that will allow a user to submit a change request.

How can I validate to ensure at least one edit is made comparing the input fields to database values?

I think the below would ensure the title entered is different from the value in 'different:', but how would I only do this for at least one field?

public function rules()
{

    return [
        'title' => [
            'required',
            'different:Dynamic Title name here',
            'string',
            'max:60',
            'not_regex:/[\x{1F600}-\x{1F64F}]/u'
        ],
        'subtitle' => [
            'string',
            'nullable',
            'max:90',
            'not_regex:/[\x{1F600}-\x{1F64F}]/u'
        ]

    ];

}

e.g. Title, Subtitle, Date fields are shown. A user must edit at least one of them from the current set database values in order to submit.

Upvotes: 0

Views: 1124

Answers (1)

Giorgi Lagidze
Giorgi Lagidze

Reputation: 831

I don't know your solution, but I'd recommend to take a look at isDirty() function.

/**
* this will return false, because after we get the record from
* database, there's no attribute of it that we changed. we just 
* print if it's dirty or not. so it tells us: "I'm clean, nobody has 
* changed my attributes at all.
*/
$role = Role::findOrFail(1);
return $role->isDirty();

/**
* lets say We fetched this role with id=1 and its status was 1. what
* this returns is still false, because even though we set the status
* attribute equal to 1, we still didn't change it. It was 1 when we
* received it from the database and it's still 1.
*/
$role = Role::findOrFail(1);
$role->status = 1;
return $role->isDirty();

/**
* now if the status was 1 in the db, and we set it to 2, it will 
* print the true.
*/
$role = Role::findOrFail(1);
$role->status = 2;
return $role->isDirty();

You can also pass an argument to isDirty() function which will only check that specific column value.

Upvotes: 1

Related Questions