How to return a json object in php laravel?

by cali_green , in category: PHP Frameworks , 9 days ago

How to return a json object in php laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 8 days ago

@cali_green 

To return a JSON object in a Laravel controller, you can use the response()->json() method. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public function getJsonData()
{
    $data = [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'phone' => '123-456-7890'
    ];

    return response()->json($data);
}


In this example, we are creating an array $data with some sample data and returning it as a JSON response using the response()->json() method. You can call this getJsonData method from your routes to get the JSON data.