How to return value as json in laravel?

by jasen_gottlieb , in category: PHP Frameworks , a year ago

How to return value as json in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a year 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' => 'johndoe@example.com',
    ];

    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' => 'johndoe@example.com',
    ];

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


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

Related Threads:

How to return empty json as {} in laravel?
How to return json in Laravel controller?
How to return a json object in php laravel?
How to convert json to value in laravel?
How to fetch specific value from json in laravel?
How to update json key value in laravel?