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]]);
1

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.