Laravel uses collection classes as common data storage. But while creating APIs JSON is an idle data type to return response data instead of a collection.
In this tutorial, you will learn how to convert collection data into JSON strings. Those data can be a model instance or even a manually created collection. We will convert the collection object into a JSON string using multiple methods.
Here, we will take multiple examples with different methods because it’s based on the use case. Let’s suppose, we are getting data from the database and you need to convert collection data into JSON then you can use the toJson() collection method. Or you need to return JSON data as API response then you can use json() method of the response class.
Last, you want to use the PHP json_encode method on collection then you use it. Let’s take examples for all methods.
Using toJson() Method
The toJson() method is a collection method that converts the collection into JSON strings. You can directly chain it into an Eloquent query and get the value as JSON.
Before using this method we have to get data from Eloquent builder using the get() or find() method. Let’s take an example of the toJson() method:
<?php
namespace App\Http\Controllers;
use App\Models\User;
class HomeController extends Controller
{
public function users(){
$user = User::whereId(1)->get()->toJson();
//OR
$user = User::find(1)->toJson();
return $user;
}
}
In the above example, we will find a user by ID and convert data into JSON objects. We just chain toJson() method on eloquent query builder.
Using json_encode() method
The json_encode() method is a primary function of PHP itself so we can use it without any dependency on Laravel. It requires only one parameter which is data, there are also some optional flags like JSON_PRETTY_PRINT or JSON_NUMERIC_CHECK which we can pass.
<?php
namespace App\Http\Controllers;
use App\Models\User;
class HomeController extends Controller
{
public function users(){
$users = User::latest()
->take(10)
->get();
return json_encode($user);
}
}
JSON Response Method
The JSON response method uses a response class to convert array or collection data into JSON objects While creating APIs, the json() function is used to convert the collection into JSON and return it as a response.
<?php
namespace App\Http\Controllers;
use App\Models\User;
class HomeController extends Controller
{
public function users(){
$users = User::latest()
->take(10)
->get();
return response()->json($user);
}
}
Conclusion
In this article, we have converted the collection into JSON object in multiple ways like toJson() function, json() method, and json_encode() function.