Hello Artisan, this article will show you how to convert a collection to a JSON format in Laravel. We will give you a simple example to turn collection array to JSON. We will assist you to convert collection data eloquent to json in Laravel which you can apply in Laravel 5, Laravel 6, Laravel 7, Laravel 8, Laravel 9. You will see below example laravel convert data to json example.
In some cases, you want to convert data to JSON format that manipulate from database as collection array. and there are many different ways to response data as JSON in Laravel, we will show you the different methods to turn your collection return from data to JSON format.
Let's check the following examples below:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users= User::select('username','email','created_at')->latest()->get();
dd(response()->json(['users' => $users]));
}
}
[
{
"username": 3,
"email": "cambotutorial1@example.org",
"created_at" : "2022-08-05T13:21:10.000000Z"
},
{
"username": 2,
"email": "cambotutorial2@example.org",
"created_at" : "2022-08-11T13:21:10.000000Z"
},
{
"username": 1,
"email": "cambo2@example.org",
"created_at" : "2022-08-11T13:21:10.000000Z"
}
]
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$user= User::find(2);
dd(\Response::json(['users' => $user]));
}
}
{
"username": 2,
"email": "cambotutorial1@example.org",
"created_at" : "2022-08-11T13:21:10.000000Z"
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$user = User::find(2);
dd($user->toJson());
}
}
{
"username": 2,
"email": "cambotutorial1@example.org",
"created_at" : "2022-08-11T13:21:10.000000Z"
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function index()
{
$users= User::select("id", "username")
->latest()
->take(3)
->get();
$users= json_encode($posts);
dd($users);
}
}
[
{
"username": 3,
"email": "cambotutorial1@example.org",
"created_at" : "2022-08-05T13:21:10.000000Z"
},
{
"username": 2,
"email": "cambotutorial1@example.org",
"created_at" : "2022-08-11T13:21:10.000000Z"
}
]
Hope you find this article help you. Have a nice day!!!
You might also like...
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him