Post Method with Guzzle doesn't work / Laravel 5 - laravel

I want to execute a scheduled task with laravel, which make a post with a single param.
I already checked with Postman my POST, so, I just have to hit myurl.com with param ID=188888 for instance. I get it working with postman.
So, first, I'm making the Laravel command : check:time, which just performs the post, and then, once I get it working, I will schedule it.
Thing is it appears commands is doing nothing, and I have no error logs.
So, really, it is not so easy to debug it...
Here is my Command Code:
class CheckTime extends Command
{
protected $signature = 'check:time {empId}';
protected $description = 'Check your time';
public function handle()
{
$client = new Client;
$numEmp = $this->argument('empId');
$response = $client->post('http://example.com/endpoint.php', ['ID' => $numEmp]);
var_dump($response);
}
}
When I print $response, I get:
class GuzzleHttp\Psr7\Response#495 (6) {
private $reasonPhrase =>
string(2) "OK"
private $statusCode =>
int(200)
private $headers =>
array(6) {
'date' =>
array(1) {
[0] =>
string(29) "Wed, 01 Jun 2016 00:17:52 GMT"
}
'server' =>
array(1) {
[0] =>
string(22) "Apache/2.2.3 (Red Hat)"
}
'x-powered-by' =>
array(1) {
[0] =>
string(10) "PHP/5.3.15"
}
'content-length' =>
array(1) {
[0] =>
string(3) "146"
}
'connection' =>
array(1) {
[0] =>
string(5) "close"
}
'content-type' =>
array(1) {
[0] =>
string(24) "text/html; charset=UTF-8"
}
}
private $headerLines =>
array(6) {
'Date' =>
array(1) {
[0] =>
string(29) "Wed, 01 Jun 2016 00:17:52 GMT"
}
'Server' =>
array(1) {
[0] =>
string(22) "Apache/2.2.3 (Red Hat)"
}
'X-Powered-By' =>
array(1) {
[0] =>
string(10) "PHP/5.3.15"
}
'Content-Length' =>
array(1) {
[0] =>
string(3) "146"
}
'Connection' =>
array(1) {
[0] =>
string(5) "close"
}
'Content-Type' =>
array(1) {
[0] =>
string(24) "text/html; charset=UTF-8"
}
}
private $protocol =>
string(3) "1.1"
private $stream =>
class GuzzleHttp\Psr7\Stream#493 (7) {
private $stream =>
resource(311) of type (stream)
private $size =>
NULL
private $seekable =>
bool(true)
private $readable =>
bool(true)
private $writable =>
bool(true)
private $uri =>
string(10) "php://temp"
private $customMetadata =>
array(0) {
}
}
}
I checked that $numEmp is OK, also, I printed $response and everything seems to be fine
As I said, I also execute the post with Postman, and it works, so, I don't really understand what's going on...
Any idea??

As #Denis Mysenko wisely advised, I tried:
$response->getBody()->getContents()
and found out that my post was getting a SQL error message.
Solution: to pass form parameters with guzzle, you have to pass it like that:
response = $client->post('http://example.com/endpoint.php', [
'form_params' => [
'ID' => $empId,
...
]
]);

Related

Laravel Http Client 419 unknown status

For testing reasons, I want to make the following Post Request with the Laravel HTTP Client:
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"zip" => "49685",
"city" => "BÜHREN",
"street" => "MÜHLENKAMP 3",
"contact_name" => "FABIANLUKASSEN",
"phone1" => "017691443785",
"email" => "FABIANLUKASSEN#TESTEN.DE",
"website" => "www.fabianlukassen.de",
"category" => "Hotel",
"closed_until" => now(),
"appointment_end" => now()->addDays(1),
"appointment_comment" => "HALLO ICH BIN FABIAN",
"additional_contacts" => "",
"phone2" => "",
"sub_category" => "",
"expert_status" => 0
]);
I know that the route is working just fine. However, with debugging in phpStorm, I can see that the $test variable contains a 419 error (unknown status). Does anyone know what's wrong?
(I'm using laravel 8)
I agree with #ElektaKode that the issue is likely due to lack of csrf token.
In order to disable CSRF middleware while testing,
switch off CSRF token for this route at /app/Http/Midddleware/VerifyCsrfToken.php, by updating:
protected $except = [ 'your-route-url' ];
Then you can use api authentication to follow it up.
The simplest way to use api authentication, follow this doc,
The other ways are either using Laravel passport or using jwt for api.(both will consume more time to set up, as you are using for testing using api authentication is your go to method.)
Usually in Laravel, 419 Page Expired error comes from CSRF middleware meaning there was a failure while validating CSRF token. Add your CSRF token to your test request or consider disabling CSRF middleware while testing.
Post Request with Laravels HTTP Client
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"place_id" => null,
"street" => "MÜHLENKAMP 3",
"zip" => "49685",
"city" => "BÜHREN",
"title" => null,
"contact_name" => "FABIANLUKASSEN",
"additional_contacts" => null,
"phone1" => "+49 163 3006603",
"phone2" => null,
"email" => "FABIANLUKASSEN#TESTEN.DE",
"category" => "Hotel",
"sub_category" => null,
"website" => "www.fabianlukassen.de",
"status" => 1,
"expert_status" => 0,
"coordinates" => null,
"expert_id" => 1,
"agent_id" => null,
"blocked" => 0,
"important_note" => null,
]);
Route
Route::apiResource('users.leads', UserLeadController::class);
Store Method in the UserLeadController
public function store(User $user, CreateLeadRequest $request)
{
//TODO: Relocate validation to request class
if(!UserLeadController::isPhone("test", $request->phone1)) {
abort(400, "Keine gültige Telefonnummer!");
return;
}
if(!UserLeadController::isPhoneNumberUnique("test", $request->phone1)) {
abort(400, "Die Telefonnummer existiert bereits!");
return;
}
/**
* The logged in User
* #var User $agent
*/
$agent = Auth::user();
$phoneUtil = PhoneNumberUtil::getInstance();
$lead = new Lead();
$lead->fill($request->except(['appointment_end', 'appointment_comment']));
// Leads created by experts will be blocked
if ($user->id === $agent->id) {
$lead->blocked = true;
}
$numberProto = $phoneUtil->parse($lead->phone1, 'DE');
$lead->phone1 = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL);
try {
$lead->save();
} catch (QueryException $e) {
//$message = 'Lead besteht bereits.';
//return Response::json(['errors' => $message], 422);
abort(422, "Lead besteht bereits!");
return;
}
if ($request->closed_until) {
$lead->closed_until = Carbon::create($request->closed_until);
$event_end = $request->appointment_end
? Carbon::parse($request->appointment_end)
: Carbon::parse($request->closed_until)->addMinutes(90);
$lead->calendarEvents()->save(new CalendarEvent([
'body' => $request->appointment_comment ?? "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'type' => CalendarEventType::CALLCENTER_APPOINTMENT,
'event_begin' => $lead->closed_until,
'event_end' => $event_end,
]));
$lead->status = LeadState::APPOINTMENT;
$lead->expert_status = LeadExpertAcceptance::ACCEPTED;
} else {
$lead->status = LeadState::OPEN;
}
if (isset($request->agent)) {
$lead->agent_id = $request->agent;
}
try {
$user->leads()->save($lead);
$lead->comments()->save(new Comment([
'body' => "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'CREATED',
'date' => now('Europe/Berlin'),
]));
if ($request->closed_until) {
$lead->comments()->save(new Comment([
'body' => "Termin wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " vereinbart.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'APPOINTMENT',
'date' => now('Europe/Berlin')->addMinute(),
]));
}
} catch (QueryException $e) {
//not sure if this works
$message = $e->getMessage();
abort(400, $message);
return;
}
if (empty($message)) {
return Response::json(['message' => 'Lead saved', 'lead' => new LeadSingleResource($lead)]);
} else {
return Response::json(compact('message'), 500);
}
}
//TODO: relocate function to rule object
protected static function isPhoneNumberUnique($attribute, $value) {
$withSpace = PhoneFormatter::formatInternational($value);
$withoutSpace = preg_replace('/ /', '', $withSpace);
$protos = [$withSpace, $withoutSpace]; // Necessary because legacy (25.06.2020).
$booleanTest = Company::query()->whereIn('phone', $protos)->doesntExist()
|| Lead::query()->whereIn('phone1', $protos)->orWhereIn('phone2', $protos)->doesntExist();
return $booleanTest;
}
//TODO: relocate function to rule object
protected static function isPhone($attribute, $value) {
if (!$value) {
return false;
}
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$test = $phoneUtil->isValidNumber($phoneUtil->parse($value, 'DE'));
return $test;
}
fillable variable in the Lead Model
protected $fillable = [
'company_name',
'place_id',
'street',
'zip',
'city',
'title',
'contact_name',
'additional_contacts',
'phone1',
'phone2',
'email',
'category',
'sub_category',
'website',
'status',
'expert_status',
'coordinates',
'expert_id',
'agent_id',
'blocked',
'important_note'
];
As mentioned before, I receive a 200 OK status. Also, in a Vue.js component, I have done the following axios post request, which also just works fine.
axios
.post(`/api/users/${this.user_id}/leads`, {
"company_name": this.companyName,
"zip": this.zipCode,
"city": this.city,
"street": this.streetAndHouseNumber,
"contact_name": this.contactPartner,
"phone1": this.contactPartnerPhoneNumber,
"email": this.contactPartnerEmail,
"website": this.website,
"category": this.category,
"closed_until": this.appointmentStart,
"appointment_end": this.appointmentEnd,
"appointment_comment": this.comment,
//not used but needed (don't know the purpose)
"additional_contacts": "",
"phone2": "",
"sub_category": "",
"expert_status":this.expert_status,
}).then(() => {
window.location.href = this.routeSuccess;
}).catch((error) => {
this.showErrorAlert = true;
this.errorAlertMessage = error.response.data.message;
});
}

Laravel error: 'preg_replace(): Parameter mismatch' on multiple file upload insert

I've got a form which allows for multiple entries into a database. Each of these rows contains a file upload field.
The fields are created as follows:
{{ Form::select('revision[]', ['0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6'], '0', ['class' => 'form-control artwork-revision']); }}
{{ Form::text('product[]', false, ['class' => 'form-control artwork-product', 'placeholder' => 'Please enter the product name']) }}
{{ Form::file('file[]', ['class' => 'artwork-file']) }}
My controller has a foreach loop to enter each row into the database but when I run it, I get the following error message: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
The code works when it's adapted for a single file upload (i.e. without the foreach loop and with only one row to be inserted, fields created without the square brackets)
How can I get past this error and enter the info into the database?
Here is the foreach loop in my controller and a var_dump of the object.
Controller foreach loop:
$files = Input::file('file');
foreach($files as $file) {
// it's a new artwork row
$artwork = new Artwork;
// get the vars
$artwork->job_id = Input::get('job_id');
$artwork->revision = Input::get('revision');
$artwork->product = Input::get('product');
// it's pending
$artwork->status = 'P';
// sort the filename...
$filename = $file->getClientOriginalName();
$file = $file->move(base_path() . '/public/artwork/' . Input::get('job_id'), $filename);
// ...and put it in the $artwork object
$artwork->filename = 'artwork/' . $artwork->job_id . '/' . $filename;
// save it
$artwork->save();
}
var_dump($artwork) output - note that only one image filename is showing in this rather than two:
object(Artwork)#243 (21) {
["dates":protected]=>
array(1) {
[0]=>
string(10) "deleted_at"
}
["fillable":protected]=>
array(6) {
[0]=>
string(6) "job_id"
[1]=>
string(8) "filename"
[2]=>
string(6) "status"
[3]=>
string(8) "revision"
[4]=>
string(7) "product"
[5]=>
string(6) "reason"
}
["table":protected]=>
string(8) "artworks"
["connection":protected]=>
NULL
["primaryKey":protected]=>
string(2) "id"
["perPage":protected]=>
int(15)
["incrementing"]=>
bool(true)
["timestamps"]=>
bool(true)
["attributes":protected]=>
array(5) {
["job_id"]=>
string(1) "5"
["revision"]=>
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "0"
}
["product"]=>
array(2) {
[0]=>
string(15) "Twist USB Drive"
[1]=>
string(19) "Eco Twist USB Drive"
}
["status"]=>
string(1) "P"
["filename"]=>
string(24) "artwork/5/12345-test.jpg"
}
["original":protected]=>
array(0) {
}
["relations":protected]=>
array(0) {
}
["hidden":protected]=>
array(0) {
}
["visible":protected]=>
array(0) {
}
["appends":protected]=>
array(0) {
}
["guarded":protected]=>
array(1) {
[0]=>
string(1) "*"
}
["touches":protected]=>
array(0) {
}
["observables":protected]=>
array(0) {
}
["with":protected]=>
array(0) {
}
["morphClass":protected]=>
NULL
["exists"]=>
bool(false)
["forceDeleting":protected]=>
bool(false)
}
This is my new 'store' controller that solves the issue:
$artwork = new Artwork;
// standard bits
$artwork->job_id = Input::get('job_id');
$artwork->status = 'P';
// variables
$artwork->revision = Input::get('revision');
$artwork->product = Input::get('product');
$artwork->file = Input::file('file');
// count how many pieces of artwork are being uploaded (this could be any field)
$count = count($artwork->revision);
/* multi-file upload */
$i = 0;
// process each piece
foreach($artwork as $a) {
while($count > $i) {
// it's a new piece of artwork
$a = new Artwork;
// standard bits to object
$a->job_id = $artwork->job_id;
$a->status = $artwork->status;
// revision and product name to object
$a->revision = $artwork->revision[$i];
$a->product = $artwork->product[$i];
// get the file and move it
$file = $artwork->file[$i];
$filename = $file->getClientOriginalName();
$movefile = $file->move(base_path() . '/public/artwork/' . $artwork->job_id, $filename);
// filename to object
$a->filename = $filename;
// save the object to db
$a->save();
// add 1 to the count
$i++;
}
}
return Redirect::route('jobs.index');
I think you can't even select multiple files. Replace your file field with this one it has multiple attribute set to true which will allow multiple files to be selected at once and returns an array of files.
{{ Form::file('file[]', ['class' => 'artwork-file','multiple' => true]) }}

Unable to implement mongor bundle in laravel

I am trying to implement mongor bundle for laravel version 3.2.14
I have followed all the steps as mentioned in the documentation on mongor homepage
There is no documentation regarding its usage in the homepage but by chance i got the following link : bundle full example
In-spite of following this i am unable to understand why my code is not working.
Strangely i am not getting any errors.
My code is as follows
database.php
'mongor' => array(
'hostname' => '127.0.0.1',
'connect' => true,
'timeout' => '',
'replicaSet' => '',
'db' => 'census',
'username' => 'root',
'password' => '',
),
user.php(Model)
class User extends Mongor\Model{
public static $timestamps = true;
public function __construct($connection = NULL)
{
parent::__construct($connection);
static::$collection = 'user';
}
}
user.php(Controller)
public function get_index()
{
//return View::make('user.index');
$users = User::first();
dd($users);
}
I am getting following data when i execute this url:
object(User)#28 (14) {
["connection"]=>
object(Mongor\MongoDB)#29 (4) {
["_name":protected]=>
NULL
["_connected":protected]=>
bool(true)
["_connection":protected]=>
object(Mongo)#30 (4) {
["connected"]=>
bool(true)
["status"]=>
NULL
["server":protected]=>
string(19) "mongodb://localhost"
["persistent":protected]=>
NULL
}
["_db":protected]=>
object(MongoDB)#31 (2) {
["w"]=>
int(1)
["wtimeout"]=>
int(10000)
}
}
["exists"]=>
bool(false)
["attributes"]=>
NULL
["dirty"]=>
array(0) {
}
["ignore"]=>
array(0) {
}
["includes"]=>
array(0) {
}
["relating"]=>
NULL
["relating_key"]=>
NULL
["relating_table"]=>
NULL
["_limit"]=>
NULL
["_skip"]=>
NULL
["_where"]=>
array(0) {
}
["_sort"]=>
array(0) {
}
["_count":protected]=>
NULL
}
Whereas when i execute the command db.user.find() in the mongo shell i get all the relevant results.

Zend Log - Bad Log Priority

When I try to add a registerErrorHandler() to my log config in my bootstrap it gives the following error:
<b>Fatal error</b>: Uncaught exception 'Zend_Log_Exception' with message 'Bad log priority' in /public/fb/library/Zend/Log.php:280
Stack trace:
#0 /public/fb/application/Bootstrap.php(24): Zend_Log->__call('registerErrorHa...', Array)
#1 /public/fb/application/Bootstrap.php(24): Zend_Log->registerErrorHandler()
#2 /public/fb/library/Zend/Application/Bootstrap/BootstrapAbstract.php(666): Bootstrap->_initLogging()
#3 /public/fb/library/Zend/Application/Bootstrap/BootstrapAbstract.php(619): Zend_Application_Bootstrap_BootstrapAbstract->_executeResource('logging')
#4 /public/fb/library/Zend/Application/Bootstrap/BootstrapAbstract.php(583): Zend_Application_Bootstrap_BootstrapAbstract->_bootstrap(NULL)
#5 /public/fb/library/Zend/Application.php(355): Z in
<b>/public/fb/library/Zend/Log.php</b> on line <b>280</b>
Bootstrap.php
protected function _initLogging(){
$log = new Zend_Log();
$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH .'/../data/logs/app.log');
$log->addWriter($writer);
$log->registerErrorHandler();
}
Output Zend_Debug::dump($log):
object(Zend_Log)#20 (6) {
["_priorities":protected] => array(8) {
[0] => string(5) "EMERG"
[1] => string(5) "ALERT"
[2] => string(4) "CRIT"
[3] => string(3) "ERR"
[4] => string(4) "WARN"
[5] => string(6) "NOTICE"
[6] => string(4) "INFO"
[7] => string(5) "DEBUG"
}
["_writers":protected] => array(1) {
[0] => object(Zend_Log_Writer_Stream)#21 (3) {
["_stream":protected] => resource(59) of type (stream)
["_filters":protected] => array(0) {
}
["_formatter":protected] => object(Zend_Log_Formatter_Simple)#22 (1) {
["_format":protected] => string(51) "%timestamp% %priorityName% (%priority%): %message%"
}}}
["_filters":protected] => array(0) {
}
["_extras":protected] => array(0) {
}
["_defaultWriterNamespace":protected] => string(15) "Zend_Log_Writer"
["_defaultFilterNamespace":protected] => string(15) "Zend_Log_Filter"
}
Thx for helping.
The error is thrown in Zend_Log::__call() magic method. since __call() is being used, this means that the referenced method does not exist in the object explicitly, so PHP has called the object's __call() magic method.
Are you sure there is no typo in the name of the method right where you are calling it?
Are you sure the version of ZF you are using actually supports this method? I checked my ZF installation (1.11.4) and on line 280 of Zend/Log.php file there is something else not related to this issue.
Updating your ZF installation to the last version could be helpful.

Having trouble processing XML with PHP SimpleXML

http://pastie.org/1701923 Here is the XML being returned from an API I am querying for zip codes.
I want to pull the data out of each entry and either loop it directly or put it into an array that I can loop. I can't seem to get it right. Here is the latest code I was using:
$xml = new SimpleXMLElement($results);
foreach($xml->zipcoderadius->zipcodes as $loc) {
$codes[] = (string)$loc['zipcode'];
}
print_r($codes);
die();
($results is the returned XML from CURL)
What is being output is Array ( [0] => [1] => [2] => [3] => [4] => )
I think this was,n be a string (zipcode). Try without string
I am not sure you're addressing the zip code correctly. For me the following works, assuming you stored your cURL result in $xmlStr previously.
$push = array();
$foo = simplexml_load_string($xmlStr);
foreach($foo->zipcoderadius->zipcodes->id as $bar) {
array_push($push, (string)$bar);
}
print_r($push);
Leading to the following output:
Array
(
[0] => 75969
[1] => 75970
[2] => 75971
)
By the way: the SimpleXML object looks like this:
object(SimpleXMLElement)#1 (1) {
["zipcoderadius"]=>
object(SimpleXMLElement)#4 (1) {
["zipcodes"]=>
object(SimpleXMLElement)#3 (32) {
["id"]=>
array(3) {
[0]=>
string(5) "75969"
[1]=>
string(5) "75970"
[2]=>
string(5) "75971"
}
["zipcode"]=>
array(3) {
[0]=>
string(5) "94945"
[1]=>
string(5) "94945"
[2]=>
string(5) "94945"
}
...

Resources