How to return value as json in laravel?

by jasen_gottlieb , in category: PHP Frameworks , 5 months ago

How to return value as json in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 5 months ago

@jasen_gottlieb 

To return a value as JSON in Laravel, you can use the response helper function along with the json method.


Here is an example of how to return a value as JSON:

  1. Inside your controller method, use the response function and chain the json method onto it.
1
2
3
4
5
6
7
8
9
public function getJsonData()
{
    $data = [
        'name' => 'John Doe',
        'email' => '[email protected]',
    ];

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


  1. You can also use the json method directly on the response instance.
1
2
3
4
5
6
7
8
9
public function getJsonData()
{
    $data = [
        'name' => 'John Doe',
        'email' => '[email protected]',
    ];

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


In both cases, the response will be converted to a JSON format and the appropriate headers will be set automatically.