0

I am a newbie in PHP. I created a Laravel project using *composer**. My controller has two endpoint uploadFile and testpost:

public function uploadFile(Request $request) {
    //there are more code about reading uploaded file here. Everything is OK here.

    $request = Request::create('/api/testpost', 'POST',
        [],[],[],[],'{"this is" : "my test content"}');
    return Route::dispatch($request);
}

public function testpost(Request $request){
    Log::info($request->all());

    return response()->json(["title"=>"this is the test get method"]);
}

uploadFile is invoked by POST action from a form which carries an uploaded JSON file. I want to call testpost inside of uploadFile method using Request::create(...) and Route::dispatch(...). testpost is invoked however the body of request is not as expected. The log file shows me that $request->all() does not return the request body which I expect to be {"this is" : "my test content"}.

My log file:

[2019-02-23 12:16:47] local.INFO: array (
  '_token' => 'JzQjclRD4WaTkezqLxlU48D1dM7S3X2X3hok3kr4',
  'employee_file' => 
  Illuminate\Http\UploadedFile::__set_state(array(
     'test' => false,
     'originalName' => 'test_input_file.txt',
     'mimeType' => 'text/plain',
     'error' => 0,
     'hashName' => NULL,
  )),
)

What wrong in my code? API invocation or request body retrieval? I know that we can call testpost method directly instead of calling API. However, I ultimate purpose is to know how to call an internal API.

3
  • That's a very weird method to dispatch requests, and I think the reason of your issue is that original request is overlaps that you created manually. Commented Feb 23, 2019 at 18:10
  • I would expect something like HttpClient in .Net but I could not find it. Commented Feb 24, 2019 at 0:48
  • If you were using laravel/installer that you also have GuzzleHttp/Guzzle package installed globally. That's what you'd want to use. Docs: docs.guzzlephp.org/en/stable Commented Feb 24, 2019 at 7:28

1 Answer 1

1

You don't need to use internal API calls for this.

If both methods are in the same class you can invoke directly with

$this->methodName($args);

and it will return the result directly to the calling function. (provided you have a return statement in the method you are invoking)

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

1 Comment

I know what you mean. Actually, I need to create two projects, one for the API, another one for the web app which calls that API. I just make the first step by calling the internal API like that to learn how to call API using PHP.

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.