How to return data in json format in Laravel

Created 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":"ziemann.eldora@example.net","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":"torey68@example.org","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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.