Saturday, February 19, 2022

[FIXED] Laravel Validation Integer accepts empty string?

Issue

Im creating some small API with which i can create blog posts through postman. Im using laravel 5 and i encoutered a problem.

In the API call, i can specify a user id, so the post is written by someone else than whoever makes the API call right now. My currently logged in user is specified with a token in postman.

So my problem is now, when i create the API call and specify my user_id as empty string "userID": ""

it will throw an error, because i specified the id to be an int like so

'userID' => ['integer']

The error is

"Type error: Argument passed to construct() must be of the type integer or null, string given",

Why does it accept an empty string? How can i validate that correctly? Note that the userID doesn't have to be specified in the post request. If not specified, it will just take the one from the user you are currently logged in with. (Specified in the token)


Solution

Using two validation rules together will fix the issue. required and integer

and as you said, you dont want to make it mandatory:

use these validation rules combination:

nullable|integer


Answered By - Himanshu Upadhyay

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.