DEV Community

Philip Perry
Philip Perry

Posted on

4

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more