yassine j
yassine j

Reputation: 515

Laravel | PHP | How to use file_get_contents?

I want to learn and to understand how can i use data, sent from an external server into my laravel project.

So i made this route :

Route::get('/receive','MyController@Receive');

And in Controller i did that :

 public function Receive(Request $request){
     $data = file_get_contents("php://input");
     $json_dat = json_decode($data, true);
     echo $json_dat;
 }

Using POSTMAN, i sent i POST request to `http://my_domain/receive

With Body > Row > JSON APP And a simple table like that : `

[{
    "type_3": "Hero",
 }]

When executing the URL in Postman, nothing happens in echo $json_dat

What I'm expecting is : Json data with type_3 : Hero

Thank you in advance

Postman action

Upvotes: 1

Views: 2896

Answers (3)

Use post instead get in router


Route::post('/receive','MyController@Receive');

in controller

public function Receive(Request $request){


    $request->json('type_3'); // hero  get from json

    $request->input('type_3'); // get from input



   return $request->all(); //return all input,request or json and vs vs
 }



Upvotes: 0

arma
arma

Reputation: 4124

As stated by Curtis, the first thing you need to do is to change the route from get to post.

Next, you want to send valid json request body with proper Content-Type:application/json header:

{  
   "type_3":"Hero"
}

In the controller itself, you do not need to manually retrieve input as Laravel is smart enough to be able to capture and parse json for you.

You can access your values using the request object $request->input('type_3') or $request->all() or many more functions for this purpose such as json(), post() etc.

Hope you can figure out based on this.

Upvotes: 1

Curtis
Curtis

Reputation: 2704

Very simple, you're expecting a GET request rather than POST.

change

Route::get('/receive','MyController@Receive');

to

Route::post('/receive','MyController@Receive');

Upvotes: 1

Related Questions