Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rublopweb's avatar

Validation rules for a json

Hi, i have a json column in one of the tables in my database. The column is called "sections_details". In my model i have this

protected $casts = [
        'sections_details' => 'array'
    ];

I have added validation using a class that extends FormRequest, and i have defined the rules function like this

 'sections_details'=> 'required|json'

The problem is that i am sending a json using postman

 "sections_details":{
        "section": "1",
        "hours": "3 a 9"
        }

The validation fails and it tells me that the json must be a valid string. I know i can use \ in postman before the quotes to send the json correctly but i do not want that. I have thought of using the prepareForValidation method

protected function prepareForValidation()
{
    $this->merge([
        'sections_details' => json_decode($this->sections_details, true)
    ]);
}

But it tells me that the first argument of the json_decode function must be a string and an array was given. Is there any way to solve this problem? Thanks a lot

0 likes
3 replies
LaryAI's avatar
Level 58

The issue you're facing is due to the fact that Laravel automatically decodes JSON input to arrays. So when you're trying to validate it as a JSON string, it fails because it's already an array.

You can solve this by creating a custom validation rule. Here's how you can do it:

First, create a new rule using Artisan command:

php artisan make:rule IsValidJson

This will create a new rule in app/Rules directory. Open the IsValidJson.php file and modify the passes method like this:

public function passes($attribute, $value)
{
    return is_array($value) || is_object(json_decode($value));
}

This rule will pass if the value is an array (which means Laravel has already decoded it) or if it's a valid JSON string.

Then, in your FormRequest, you can use this rule like this:

use App\Rules\IsValidJson;

public function rules()
{
    return [
        'sections_details' => ['required', new IsValidJson],
    ];
}

This way, your validation will pass whether the JSON is already decoded or not.

krisi_gjika's avatar

"But it tells me that the first argument of the json_decode function must be a string and an array was given. Is there any way to solve this problem?"

Yes the framework is decoding the json in an array for you based on the headers postman has applied for you. Validate the field as any other array field and save it to your model. The cast will take care to create a json from the array to store in the DB.

Please or to participate in this conversation.