Foreach Loop not running in Laravel - laravel

I want to send a request to external API using guzzle, but not foreach is not running.
public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now());
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);
It worked if I hardcode the value into the form paramas.

public function recursub() {
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
//Get all Check User
foreach ($usersCheck as $user) {
dd('Hello');
$url = 'https://api.##############';
$client = new Client();
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.'#########################',
'Content-Type' => 'application/json'
],
'form_params' => [
'authorization_code' => $user->authorization_code,
'customer' => $user->email,
//'plan' => '#######################',
]
]);

get() method is used to get data in array, so now you have to add get() method in the last of the query. Here is the code below:
$usersCheck = User::where('trialExpires', '<=', Carbon::now())->get();
get() method is used for getting multiple records and first is used for single record.

Related

POST request with axios gets treated as GET nuxt to Laravel

I'm making a request to my laravel backend.
But the request gets treated as a GET instead of a POST, I can't find that the problem is..
here is the function:
this.$axios
.post('/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})
and trying to recieve it in this controller function:
public function createCar(Request $request) {
$title = $request->title;
$previewText = $request->previewText;
$fuel = $request->fuel;
$gearbox = $request->gearbox;
$brand = $request->brand;
$model = $request->model;
$year = $request->year;
$miles = $request->miles;
$price = $request->price;
$carType = $request->carType;
$images = $request->images;
$car = Car::create([
'title' => $title,
'previewText' => $previewText,
'fuel' => $fuel,
'gearbox' => $gearbox,
'brand' => $brand,
'model' => $model,
'year' => $year,
'miles' => $miles,
'price' => $price,
'carType' => $carType
]);
// store each image
foreach($images as $image) {
$imagePath = Storage::disk('uploads')->put('/cars' . '/' . $car->id, $image);
carImage::create([
'carImageCaption' => $title,
'carImagePath' => 'uploads' . $imagePath,
'carId' => $car->id
]);
}
return response()->json(['errors' => false, 'data' => $car]);
}
here is the route:
Route::group(['middleware' => 'throttle:20.5'], function () {
Route::post('/create_car', 'CarController#createCar');
});
in the xamp log it seems like it sends two request first a POST and then a GET 3 seconds apart
Ok to fix this you need to call the route properly, since the route inside your api.php call it like this:
this.$axios
.post('/api/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})

Laravel - How to pass the result of Post Request

I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}

Guzzle HTTP POST request in laravel

how to pass path parameter in guzzle HTTP Post request. I am having url like this - http://base_url/v1/rack/{id}/books
in my url {id} is the path parameter.
$addLibraryUrl = $base_url."v1/rack/{id}/book";
$headers["id"] = $id;
$requestContent['json'] = $data;
$client = new Client();
$response = $client->post($addLibraryUrl, [
"headers" => $headers,
"json" => json_encode($data)
]);
I dont think the latest guzzle uses URI templates, but the functionality to do the parameter replacing is still there:
$addLibraryUrl = \GuzzleHttp\uri_template($base_url. "v1/rack/{id}/book" , [
'id' => $id,
]);
Also you can just put the id into the URI yourself very easily.
$addLibraryUrl = $base_url."v1/rack/{$id}/book";
example:
blah.com/v1/rack/5/book
I solved my issue in this way:
$id = your_rack_id_value;
$client = new Client([ 'base_uri' => $base_url, ]);
$uri = 'v1/rack/.$id.'/book';
$requestEncodedData = json_encode($data);
$response = $client->post($uri, [
'body' => $requestEncodedData,
'headers' => [
'Content-Type' => 'application/json',
]
]);
If you sent form params then you need to sent them as post params like :
// Initialize Guzzle client
$client = new GuzzleHttp\Client(['headers'=> 'Some headers']);
// Create a POST request
$response = $client->request(
'POST',
'http://yoururl.com',
[
'form_params' => [
'key1' => 'value1',
'key2' => 'value2'
]
]
);
Or like in your case change 'json' to form_params:
$addLibraryUrl = $base_url."v1/rack/{id}/book";
$headers["id"] = $id;
$requestContent['json'] = $data;
$client = new Client();
$response = $client->post($addLibraryUrl, [
"headers" => $headers,
"form_params" => json_encode($data)
]);

Guzzle - Laravel. How to make request with x-www-form-url-encoded

I need to integrate an API so I write function:
public function test() {
$client = new GuzzleHttp\Client();
try {
$res = $client->post('http://example.co.uk/auth/token', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'json' => [
'cliend_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
$res = json_decode($res->getBody()->getContents(), true);
dd($res);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
as a responde I got message:
{"data":{"error":"invalid_clientId","error_description":"ClientId should be sent."}}
Now when I try to run the same url with same data in POSTMAN app then I get correct results:
What is bad in my code? I send correct form_params also I try to change form_params to json but again I got the same error...
How to solve my problem?
The problem is that in Postman you're sending the data as a form, but in Guzzle you're passing the data in the 'json' key of the options array.
I bet that if you would switch the 'json' to 'form_params' you would get the result you're looking for.
$res = $client->post('http://example.co.uk/auth/token', [
'form_params' => [
'client_id' => 'SOMEID',
'client_secret' => '9999jjjj67Y0LBLq8CbftgfdreehYEI=',
'grant_type' => 'client_credentials'
]
]);
Here's a link to the docs in question: http://docs.guzzlephp.org/en/stable/quickstart.html#sending-form-fields
Also, I noticed a typo - you have cliend_id instead of client_id.

laravel guzzle httpsocket parameters for ssl verify peer & host

I have the following code in CakePHP. I need the same code in laravel using guzzle
$url = "https://xyz?";
$query ='first_name='. $data->FirstName .'&gender=""'. '&home_phone='. $data->HomePhone.'&ip_address='. $data->IPAddress.'&last_name='. $data->LastName.'&user_defined_url='. $result;
$HttpSocket = new HttpSocket(array('ssl_verify_peer' => false, 'ssl_verify_host' => false));
$post_response = $HttpSocket->get($url,$query);
$response = explode('&',$post_response->body);
I have converted it in laravel using guzzle but doesnt work. Following my code that Ive converted in laravel:
$client = new Client(['verify' => false ]);
$post_response = $client->get($url, $query);
$response = explode('&',$post_response->body);
Note: use GuzzleHttp\Client; is written at the top of file.
Thanks in advance for the help!
Can you try like this,
$client = new Client();
$post_response = $client->request('GET', $url, [
'verify' => false,
'form_params' => [
'first_name' => $data->FirstName,
'gender' => "",
'home_phone' => $data->HomePhone,
'ip_address' => $data->IPAddress,
'last_name' => $data->LastName,
'user_defined_url' => $result
]
]);
$response = explode('&',$post_response->body);
Instead of form_params you can use query for sending the parameters as query string.

Resources