How to return data in json format in Laravel

Updated at 07-Aug-2022, By samar

How to return data in json format in Laravel

With this article, we’ll look at some examples of how to address the "How to return data in json format in Laravel" problem.

I got the user records using **`get()`** method from the users table and i want to return it in json format from controller.
  • Return data in json format from controller file

    Laravel syntax to convert data in json format

    response()->json($data)
    

    Example code

    app\Http\Controllers\HomeController.php

    $data = App\Models\User::get();
    return response()->json($data);
    

    Ouput

    [{"id":1,"name":"Mr. Jay Price Jr.","email":"[email protected]","email_verified_at":"2022-03-03T11:01:39.000000Z","username":"","created_at":"2022-03-03T11:01:39.000000Z","updated_at":"2022-03-03T11:01:39.000000Z"},
    {"id":2,"name":"Prof. Jarvis Lehner","email":"[email protected]","email_verified_at":"2022-03-03T11:01:39.000000Z","username":"",
    "created_at":"2022-03-03T11:01:39.000000Z","updated_at":"2022-03-03T11:01:39.000000Z"}]

Back to code snippet queries related laravel