Laravel HTTP Client Post Response Save File - php

Sends post request to another api inside Laravel controller.
It returns .pdf file as a response. I wanna save this file to storage. I get FileNotFound exception.
Here is the code
public function cvToPDF(Request $request)
{
$response = Http::withHeaders(['Content-Type' => 'application/pdf'])
->withToken(Request()->bearerToken())
->post('http://some-endpoint', $request->all());
Storage::disk('s3')->putFile('drive/files', $response);
return $response;
}
return $response works in client side. I can download the pdf with this endpoint. But Storage::disk raises exception.

Because you try to save response, not file.
Workaround at sink() method - this MAY work.
public function cvToPDF(Request $request)
{
$tempName = tempnam(sys_get_temp_dir(), 'response').'.pdf';
$response = Http::sink($tempName)
->withHeaders(['Content-Type' => 'application/pdf'])
->withToken(Request()->bearerToken())
->post('http://some-endpoint', $request->all());
Storage::disk('s3')->putFile('drive/files', new File($tempName));
return $response;
}

Related

how to get http request detail in laravel?

I have an http client request like this?
try {
$request = json_encode($data);
$result = $this->pendingRequest->{$method}('http://test.local/general/wallets/1000000', $data);
// this is my request detail
$request = $result->transferStats ? Message::toString($result->transferStats->getRequest()) : $request;
$result->throw();
$this->setLog($provider, $step, $request, $result->body(), $url, $result->status());
return $result;
} catch (RequestException $exception) {
// I need to http request detail
} catch (ConnectionException $exception) {
// I need to http request detail
}
I need to get my request param and headers and token and every thing that send to third party in cache exceptions. I can get detail in try via: Message::toString($result->transferStats->getRequest())
you can #dd($request);
on blade OR
dd($request); on controllers etc..
Illuminate\Http\Client\Request
headers() : array
Get the request headers.
parameters() : array
Get the request's form parameters.
body() : string
Get the body of the request.
data() : array
Get the request's data (form parameters or JSON).
You can take it as
$request->all();
if you want to see more regular. you can try
dd($request->all());

Laravel HTTP Client - method chaining issue

I have been using the HTTP client in Laravel 8, as follows:
$http = Http::asForm()->post($url, $post_data);
$response = $http->body();
This works great. Now I want to include a file upload as part of this request, but the file is optional. I have tried to structure my request like this:
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Request;
public function index(Request $request)
{
$url = 'my-url';
$post_data = $request->post();
$http = Http::asForm();
if ($request->hasFile('image')) {
$http->attach('image', $request->file('image'));
}
$http->post($url, $post_data);
$response = $http->body();
}
But this is not working. The error I am getting is: Method Illuminate\Http\Client\PendingRequest::body does not exist.
The post() method appears to be returning Illuminate\Http\Client\PendingRequest instead of Illuminate\Http\Client\Response.
Any ideas how to do this?
$response = $http->post($url, $post_data)->body();
// alternatively:
$pendingRequest = $http->post($url, $post_data);
$response = $pendingRequest->body();
In your second code sample, you don't assign the return of post() to a variable. But this return value (Illuminate\Http\Client\PendingRequest) is the object that defines the body() method. So either use a second variable (or reassign $http), or chain the post() and body() calls as shown above.

Laravel: can't get post data using Postman form-data

Currently I'm developing a RESTful API so I created a method to upload images but can't the post data using Postman form-data
Here's the screenshot of the request on the Postman.
I've tried to print the request but still can't get the data.
Upload image code
public function fileUpload(Request $request, $id)
{
//print_r($request->file('photo'));
//exit;
$rules = [
'photo' => 'image|mimes:jpeg,jpg,png|max:2048'
];
$this->validate($request, $rules);
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$filename = time().'.'.$file->getClientOriginalExtension();
$request->file('photo')->move(public_path('storage/images'), $filename);
}
return response()->json(['message' => 'Image successfully uploaded'], 200);
}
I want to get post data(photo) through laravel request.

does Slim framework have URL encoded annotation for POST method?

I'm developing a web RESTful API using slim framework of php.I want to know how do I add some annotation type thing on POST method so that it can behave as URL encoded method.Please help me in this regard.Advance thanks.
There is no pre-programmed way for this - there is no Slim or php method that will definitively check if your string is urlencoded. What you can do is implement Slim Middleware to your route.
<?php
$app = new \Slim\App();
$mw = function ($request, $response, $next) {
if ( urlencode(urldecode($data)) === $data){
$response = $next($request, $response);
} else {
$response = ... // throw error
}
return $response;
};
$app->get('/', function ($request, $response, $args) { // Your route
$response->getBody()->write(' Hello ');
return $response;
})->add($mw); // chained middleware
$app->run();
Discussion: Test if string is URL encoded in PHP
Middleware: https://www.slimframework.com/docs/v3/concepts/middleware.html
Since you're using Slim as the foundation to your API, the easiest way is to just build a GET route with the desired URL parameters defined:
$app->get('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
// Route actions here
});
In your documentation, make sure you inform the consumers of this API that it is a GET endpoint, so that a POST body should not be made; rather, the parameters that you outline in the URL should be used to pass the client's data over to the API.
If you are intent on using a POST route with just URL parameters, then you could also force a response back if the route detects an incoming POST body:
$app->post('/users/filter/{param1}/{param2}/{param3}', function (Request $request, Response $response) {
$postBody = $request->getParsedBody();
if (is_array($postBody)) {
$denyMsg = "This endpoint does not accept POST body as a means to transmit data; please refer to the API documentation for proper usage.";
$denyResponse = $response->withJson($denyMsg, $status = null, $encodingOptions = 0);
return $profileData;
}
});

laravel callback url with file_get_contents('php://input')

in vanilla php i would create a callbak url with just
try
{
//response content type application/json
header("Content-Type:application/json");
//read incoming request
$postData = file_get_contents('php://input');
.......
......
but in laravel i'm yet to get a clear explanation on how to achieve the same
ive tried using
$postData = Request::getContent();
but it returns blank
If you need data in request use (new \Illuminate\Http\Request())->all() or use DI
public function someAction(\Illuminate\Http\Request $request)
{
dd($request->all());
}

Categories