0

I was looking for help creating an object of the type Illuminate\Http\Request. This article helped me understand the mechanism of the class, but I did not get the desired result.

Create a Laravel Request object on the fly

I'm editing the development code passed to me by the customer. The code has a function that gets a request parameter from vue and translates it to JSON:

$json = $request->json()->get('data');
$json['some_key'];

This code returned an empty array of data:

$json = $request->request->add([some data]);

or

$json = $request->request->replace([some data]);

this one returned an error for missing the add parameter

$json = $request->json->replace([some data]);

A variant was found by trying and errors. Maybe, it help someone save time:

public function index() {
  $myRequest = new \Illuminate\Http\Request();
  $myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
  $data = MyClass::getData($myRequest);
}

..
class MyClass extends ...
{
  public static function getData(Request $request) {
     $json = $request->json()->get('data');
     $json['some_key'];

In addition, there are other fields in the class that you can also slip data into so that you can pass everything you want via Request

$myRequest->json()->replace(['data' => ['some_key' => $some_data]]);
..        
$myRequest->request->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->attributes->replace(['data' => ['some_key' => $some_data]]);
..
$myRequest->query->replace(['data' => ['some_key' => $some_data]]);
ktscript
  • 309
  • 4
  • 11

1 Answers1

3
$myRequest = new \Illuminate\Http\Request();
$myRequest->setMethod('POST');
$myRequest->request->add(['foo' => 'bar']);
dd($request->foo);

This from the link you shared works, give it a try. Thanks for sharing that link!

Mihir
  • 43
  • 6