How to validate JSON in Laravel
I’m pretty sure if you’re older enough to be working in the software development industry, the one format that you would be working with in a recurring manner is JSON.
There are a lot of places where information is represented as JSON and when you’re working with JSON, it’s important that it’s not an invalid one to keep systems’ integrity intact.
Now, Laravel makes it pretty easy to validate JSON strings with the newly added isJson
method in Laravel 9.x.
So, for instance, let’s say we have the following JSON…
$user = '{
"name": "Cherika",
"age": 5,
"is_active": false
}';
…And if we want to validate this JSON string, here’s how we can do it.
use Illuminate\Support\Str;
$isValidUser = Str::isJson($user);
// boolean (true)
The method is also available when you’re working with fluent strings.
$isValidUser = Str::of($user)->isJson();
// boolean (true)
$isValidUser = str($user)->isJson();
// boolean (true)
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.