loading...

Validate if multiple IDs exist and store as JSON with Laravel

programmingdecoded profile image Philip Perry ・1 min read

I had a table called contact_times with these values:

"id", "name"
"1", "Mornings"
"2", "Lunchtime"
"3", "Afternoons"
"4", "Evenings"

A user can check several times when he would like to be contacted. Frontend sends the selected IDs as array to backend:

'contact_time_id' => [1, 3]

And they get saved as a JSON string in the contact_time_id column of the contact table.

How do we verify that (although unlikely to happen in this scenario), frontend doesn't send back IDs of options that don't exist in the contact_times table?

We can create a request class in Laravel and add a validation rule.

class ContactStoreRequest extends FormRequest
{  
    public function rules()
    {
        return [
            'contact_time_id.*' => 'exists:contact_times,id'
        ];
    }
}

Note the asterisk that can be used to check for multiple values, e.g. an array.

To save the array as JSON in the contacts table, we add $casts in the contact model:

class Contact extends Model
{
    protected $casts = [
        'contact_time_id' => 'json',
    ];
}

As is often the case with Laravel, if you know how, you can make the code elegant and concise.

Posted on by:

programmingdecoded profile

Philip Perry

@programmingdecoded

I write here about the joys and struggles of a software developer learning new things.

Discussion

markdown guide