Hello Geeks, This tutorial will show you how to convert a collection to JSON file in Laravel. This post will show you how to convert an object in Laravel to JSON. I’d like to demonstrate a laravel collection to json example. We will assist you in providing an example of a laravel eloquent object to json. Let’s look at an example of laravel converting data to json below.
This example is also applicable to Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions.
Example 1: get() with toJson() in laravel
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("id", "title", "body")
->latest()
->get()
->toJson();
dd($posts);
}
}
Example 2: find() with toJson() in laravel
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$post = Post::find(40)->toJson();
dd($post);
}
}
Example 3: json_encode() in laravel
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("id", "title", "body")
->latest()
->take(5)
->get();
$posts = json_encode($posts);
dd($posts);
}
}
Example 4: Custom Collection using toJson() in laravel
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = collect([
['id' => 1, 'title' => 'Title One', 'body' => 'Body One'],
['id' => 2, 'title' => 'Title Two', 'body' => 'Body Two'],
]);
$posts = $posts->toJson();
dd($posts);
}
}
Example 5: JSON Response in laravel
PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$posts = Post::select("id", "title", "body")
->latest()
->get();
return response()->json(['posts' => $posts]);
}
}
Best wishes as you code.