DEV Community

Philip Perry
Philip Perry

Posted on

Validate if multiple IDs exist and store as JSON with Laravel

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]
Enter fullscreen mode Exit fullscreen mode

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'
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

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',
    ];
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)