How to read json data in laravel controller?

Member

by deron , in category: PHP Frameworks , 15 days ago

How to read json data in laravel controller?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 14 days ago

@deron 

To read JSON data in a Laravel controller, you can use the IlluminateHttpRequest class to access the JSON data sent in the request. Here is an example of how you can read JSON data in a Laravel controller:

  1. Use the IlluminateHttpRequest class in your controller:
1
use IlluminateHttpRequest;


  1. Use the input() method of the Request object to access the JSON data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public function readJsonData(Request $request)
{
    $jsonData = $request->input('data');

    // Process the JSON data here
    // You can decode the JSON data if necessary
    $jsonDataArray = json_decode($jsonData, true);

    // Return a response
    return response()->json(['status' => 'success', 'data' => $jsonDataArray]);
}


  1. Make a POST request to the controller and send JSON data in the request body. For example, if you are using Postman, you can send JSON data like this:
1
2
3
4
5
6
{
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}


  1. Access the JSON data in the controller using the input() method as shown in step 2.


By following these steps, you can easily read JSON data in a Laravel controller.