In this article we will learn to get json post data in laravel from request. 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
Example to laravel get request json body
in this exampel we will get laravel post json body as below
$request ->json()->get("field_name")
or
$data = request()->json()->all();
$data['field_name'];
or
json_decode($request->getContent(), true);
Understand Get Json Post Data in laravel from Request In Laravel
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: