Spread the love

In this article we will learn to get json post data from request in laravel. Laravel by default supports for form-data and x-www-form-urlencode which we can get easily using the Request class as follow $request->field_name or $request->get('field_name'). To retrieve the json post data in laravel we need to call json method of request class.

While using some frontend side framework or library like react and angular technologies then they by default sent request in the form of json post request and to fetch the post json request in laravel we need to use laravel json method as follow

$request ->json()->get("field_name")

or

$data = request()->json()->all();
$data['field_name'];

or 

json_decode($request->getContent(), true);

Let’s understand it with example step by step

Step 1: Create a fresh laravel project

Open a terminal window and type below command to create a new project

composer create-project --prefer-dist laravel/laravel blog

You can also read this to start with new project

Step 2: Create Route

Next, create a route a and define a inline function in the routes as follow

<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;


Route::post("/send-json-request",function(Request $request ){
    $data = $request ->json()->all();
    dump($request ->json()->get("test"));
    dd($data);
});

Step 3 : Create Javascript Fetch API Call

To test and send a request in json post format we need to call it from either from client side or server side so we are using here JavaScript fetch method

<script>
fetch('http://localhost:8000/send-json-request', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({test: 1, b: 'Textual content'})
  }).then(data=>{

  });
</script>

ScreenShot:

Laravel json post request

Leave a Reply