Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

How to validate JSON in Laravel

June 16, 2022 ·

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)
Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?