Laravel 9 How to Convert Collection To JSON Tutorial

Reading Time: 6 minutes
1,646 Views

Inside this article we will see the concept i.e Laravel 9 How to Convert Collection To JSON. Article contains the classified information about getting collection data into JSON format. There are several ways by which we can get collection data of laravel in JSON format.

You will use toJson() method which convert your collection data into JSON. If you are wondering to find a solution to convert eloquent data into JSON format then this article will help you a lot for this.

We will cover –

  • How to convert eloquent data into json
  • How to return json response
  • How to encode data into json
  • How to convert collection data into json.

Learn More –

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Eloquent Data To JSON: get() with toJson()

We will consider a laravel controller in which we will convert eloquent data into JSON format. We will use get() and toJson() chained methods of laravel.

<?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);
    }
}

Concept

$posts = Post::select("id", "title", "body")
	        ->latest()
	        ->get()
	        ->toJson();

Output

[

   {

      "id":40,

      "title":"Post title 1",

      "body":"Post body"

   },

   {

      "id":39,

      "title":"Post title 2",

      "body":"Post body"

   },

   {

      "id":38,

      "title":"Post title 3",

      "body":"Post body"

   }

]

Eloquent Data To JSON: find() with toJson()

We will consider a laravel controller in which we will convert eloquent data into JSON format. We will use find() and toJson() chained methods of laravel.

<?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);
    }
}

Concept

$post = Post::find(40)->toJson();

Output

{

   "id":40,

   "title":"Post title 1",

   "slug":null,

   "body":"Post body",

   "created_at":"2022-08-05",

   "updated_at":"2022-08-05T13:21:10.000000Z",

   "status":1

}

Eloquent Data To JSON: Using json_encode()

We will consider a laravel controller in which we will convert eloquent data into JSON format. We will use json_encode() a PHP function.

<?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);
    }
}

Concept

$posts = Post::select("id", "title", "body")
            ->latest()
            ->take(5)
            ->get();

Output

[

   {

      "id":40,

      "title":"Post title 1",

      "body":"Post body"

   },

   {

      "id":39,

      "title":"Post title 2",

      "body":"Post body"

   },

   {

      "id":38,

      "title":"Post title 3",

      "body":"Post body"

   }

]

Custom Collection using toJson()

We will consider a custom collection and will convert into JSON format.

<?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);
    }
}

Concept

$posts = $posts->toJson();

Output

[

   {

      "id":1,

      "title":"Title One",

      "body":"Body One"

   },

   {

      "id":2,

      "title":"Title Two",

      "body":"Body Two"

   }

]

Method Response to JSON

If you are creating an API in laravel, then you can use this concept to return data via method into JSON format.

<?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]);
    }
}

Concept

return response()->json(['posts' => $posts]);

Output

{"posts":[{"id":40,"title":"Post title 1","body":"Post body"},{"id":39,"title":"Post title 2","body":"Post body"},{"id":38,"title":"Post title 3","body":"Post body"},{"id":37,"title":"Post title 4","body":"Post body"},{"id":36,"title":"Post title 5","body":"Post body"}]}

We hope this article helped you to Learn Laravel 9 How to Convert Collection To JSON Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.