Cracking the Code: Decode JSON in Laravel Like a Pro (Guaranteed Results)

 How to decode a response made with Laravel JSON syntax with Example

Cracking-the-Code-Decode-JSON-in-Laravel-Like-a-Pro-(Guaranteed Results)

JSON plays the most important role while you are working with API Development. Laravel provides lots of methods and functions to handle and deal with different types of responses. In this article we will cover a common problem people are getting while dealing with JSON.

How to decode a response made with following syntax.

  • Response::json()
  • response()->json()
If you try to decode these formats with the typical method like json_decode($data,true) then you will get NULL. So there are basically two simple methods you can use to deal with this error.

Quick Solution :-

Use of getData() function :

public function getUsers(){
        $all_users = $this->homeService->getUsers();
        $decode = $all_users->getData();
        return $decode;
    }

Use of getContent() function :

public function getUsers(){
        $all_users = $this->homeService->getUsers();
        $decode = json_decode($all_users->getContent(),true);
        return $decode;
    }


HomeService.php :-

<?php

namespace App\Services;

use JWTAuth;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;

class HomeService extends Controller
{
    public function getUsers(){
        $users = User::all();
        return response()->json(['response' => ['code' => 200, 'message' => 'List fetched successfully','data'=>$users]]);
    }
}


HomeController.php :-

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Services\HomeService;

class HomeController extends Controller
{
    protected $homeService;

    
    public function __construct(HomeService $homeService)
    { 
        $this->homeService = $homeService;
    }

    public function getUsers(){
        $all_users = $this->homeService->getUsers();
        return json_decode($all_users,true);
    }
}


With these above code you will get response as NULL . Below are the working solutions for this issue.


Solution - 1 :

public function getUsers(){
        $all_users = $this->homeService->getUsers();
        $decode = json_decode($all_users->getContent(),true);
        return $decode;
    }


Solution - 2 :

public function getUsers(){
        $all_users = $this->homeService->getUsers();
        $decode = $all_users->getData();
        return $decode;
    }


Output :-

How to decode a json made with response()->json - Laravel (100% working)


Thank you for reading this article 😊

For any query do not hesitate to comment 💬

Previous Post Next Post

Contact Form