laravel guzzlehttp - Server Exception in RequestException.php - laravel-5

I am getting ServerException in RequestException.php line 107 when I make POST request to my API. I get following error -
Server error: POST http://10.10.1.40:3000/auth/register resulted in a 500 Internal Server Error response:
{"statusCode":500,"errorMessage":"[object Object]"}.
I tried sending post request from REST Client and it works.
Following is the trace
in RequestException.php line 107 at RequestException::create(object(Request), object(Response)) in Middleware.php line 65
at Middleware::GuzzleHttp\{closure}(object(Response)) in Promise.php line 199
at Promise::callHandler('1', object(Response), array(object(Promise), object(Closure), null)) in Promise.php line 152
at Promise::GuzzleHttp\Promise\{closure}() in TaskQueue.php line 60
at TaskQueue->run(true) in Promise.php line 240
at Client->request('POST', 'http://10.10.1.40:3000/auth/register', array('body' => '{"firstName":"abc","lastName":"ab"}')) in RegisterController.php line 30
at RegisterController->postRegisterForm(object(Request))
Following is my controller code
class RegisterController extends Controller{
public function postRegisterForm(Request $request){
$jsonData = json_encode($_POST);
$client = new Client();
$res = $client->request('POST','10.10.1.40:3000/auth/register', ['body' => $jsonData]);
echo $res->getStatusCode();
echo $res->getBody();
}
}
Any suggestions?

You are right #ShaunBramley. I missed out sending the content type header in request. Adding following code works -
$headers = ['Content-Type' => 'application/json'];
$res = $client->request('POST', 'http://10.10.1.40:3000/auth/register', ['headers'=>$headers,'body' => $jsonData]);

Related

POST: 500 Internal Server Error from Messenger Bot in laravel

I setup my Webhok by Ngrok URL for my Facebook page, and I applied all of the requirements for the Messenger Platform, but when I send the messages to my Facebook page I encounter the following error:
POST /Facebook_Messenger_Token 500 Internal Server Error
and in routs file in Laravel I use Get and Post functions as follow:
Route::get('Facebook_Messenger_Token', 'MessengerController#index');
Route::post('Facebook_Messenger_Token', 'MessengerController#index');
When I send the messages I get the following error in storage/app.logs/laravel:
[2020-06-08 18:44:21] local.ERROR: Undefined variable: id {"exception":"[object] (ErrorException(code: 0): Undefined variable: id at C:\\xampp\\htdocs\\AzadApp\\app\\Http\\Controllers\\MessengerController.php:17)
[stacktrace]
my public function index:
public function index()
{
// here we can verify the webhook.
// i create a method for that.
$this->verifyAccess();
$user = json_decode($this->getUser($id)); --this is line 17
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$response = [
'recipient' => ['id' => $id ],
'message' => ['text' => "Thanks for watching {$user->first_name} {$user->last_name}! :)"]
];
$this->sendMessage($response);
}
Please support and thanks.
The $id is being defined on line 19 (that is after line 17). in order to use it on
$user = json_decode($this->getUser($id));
you should place the above line after line 19
$id = $input['entry'][0]['messaging'][0]['sender']['id'];
do not move line 19 up (as i said in my comment) instead move line 17 down since
$id = $input['entry'][0]['messaging'][0]['sender']['id'];
is using $input that is defined before.
all you have to do is move line 17 under line 19.
so the full function now should look like this:
public function index()
{
// here we can verify the webhook.
// i create a method for that.
$this->verifyAccess();
$input = json_decode(file_get_contents('php://input'), true);
$id = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
$user = json_decode($this->getUser($id));
$response = [
'recipient' => ['id' => $id ],
'message' => ['text' => "Thanks for watching {$user->first_name} {$user->last_name}! :)"]
];
$this->sendMessage($response);
}

Laravel Lumen ReflectionException

I already had a look at other post about how to fix the ReflectionException issue in laravel Lumen, using this:
$request = Illuminate\Http\Request::capture();
$app->run($request);
However it is not solving my problem. I have a controller called AccountController.php and placed in app/Http/Controllers/Account folder and here is the code:
<?php
namespace App\Http\Controllers\Account;
use App\Account;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class AccountController extends Controller {
public function createNewAccount(Request $request) {
$newAccount = Account::create($request->all());
return response()->json($newAccount);
}
}
And this is my route file placed in /routes/web.php:
<?php
$app->get('/hello', function () use ($app) {
return 'Hello World!';
});
$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers\Account'], function($app)
{
$app->post('account','AccountController#createNewAccount');
});
When I test with Postman the get request which returns a simple 'Hello World' is working fine, but the POST call to api/v1/account/createNewAccount will always fail whatever I do:
ReflectionException in Container.php line 681:
Class App\Http\Controllers\App\Http\Controllers\Account\AccountController does not exist
in Container.php line 681
at ReflectionClass->__construct('App\Http\Controllers\App\Http\Controllers\Account\AccountController') in Container.php line 681
at Container->build('App\Http\Controllers\App\Http\Controllers\Account\AccountController') in Container.php line 565
at Container->make('App\Http\Controllers\App\Http\Controllers\Account\AccountController') in Application.php line 208
at Application->make('App\Http\Controllers\App\Http\Controllers\Account\AccountController') in RoutesRequests.php line 677
at Application->callControllerAction(array(true, array('uses' => 'App\Http\Controllers\App\Http\Controllers\Account\AccountController#createNewAccount'), array())) in RoutesRequests.php line 644
at Application->callActionOnArrayBasedRoute(array(true, array('uses' => 'App\Http\Controllers\App\Http\Controllers\Account\AccountController#createNewAccount'), array())) in RoutesRequests.php line 629
at Application->handleFoundRoute(array(true, array('uses' => 'App\Http\Controllers\App\Http\Controllers\Account\AccountController#createNewAccount'), array())) in RoutesRequests.php line 528
at Application->Laravel\Lumen\Concerns{closure}() in RoutesRequests.php line 782
at Application->sendThroughPipeline(array(), object(Closure)) in RoutesRequests.php line 534
at Application->dispatch(object(Request)) in RoutesRequests.php line 475
at Application->run(object(Request)) in index.php line 29
I am using "laravel/lumen-framework": "5.4.*".
There is no reply to this particular issue, I decided to build my API with Dingo API: https://github.com/dingo/api It is a good package to build API with Laravel/lumen. They created their own routing system and things are going much better since.

Why am I receiving a Route Collection error when inserting data?

When I try to insert data in Laravel 5.3 below error shown
Whoops, looks like something went wrong.
1/1 MethodNotAllowedHttpException in RouteCollection.php line 218:
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 755
at Router->findRoute(object(Request)) in Router.php line 610
at Router->dispatchToRoute(object(Request)) in Router.php line 596
at Router->dispatch(object(Request)) in Kernel.php line 268
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in Pipeline.php line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 137
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php line 33
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 104
at Pipeline->then(object(Closure)) in Kernel.php line 150
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 117
at Kernel->handle(object(Request)) in index.php line 53
My Controller Code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\userCreate;
public function store(Request $request)
{
$newUser = new userCreate;
$newUser ->fname = $request->fname;
$newUser ->lname = $request->lname;
$newUser ->email = $request->email;
$newUser ->password = $request->password;
$newUser ->utype = $request->utype;
$newUser->save();
//return redirect('/');
}
I'll look to post my route here:
Make sure your method is POST when accessing the route that creates a new user.
Try it...I think you are using resource controller so routing may be fine.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\userCreate;
public function store(Request $request)
{
$newUser = new userCreate;
$newUser ->fname = $request->input('fname');
$newUser ->lname = $request->input('lname');
$newUser ->email = $request->input('email');
$newUser ->password = $request->input('password');
$newUser ->utype = $request->input('utype');
$newUser->save();
//return redirect('/');
}
Use POST method when accessing the route that creates a new user.
Route::post('/store', 'NameController#store');
your route should be as below :
Route::resource('store','ControllerName');
if still not working, add your routes.php to Question.

Trying to get property of non-object when generating a Carbon date from controller

When a new user registers to my app, I'm trying to create new row in the registrations table that contains a timestamp column.
I get the following error:
ErrorException in Registration.php line 111: Trying to get property of non-object
in Registration.php line 111
at HandleExceptions->handleError('8', 'Trying to get property of non-object', '/app/Registration.php', '111', array('registration_time' => object(Carbon))) in Registration.php line 111
at Registration->setRegistrationTimeAttribute(object(Carbon)) in Model.php line 2863
at Model->setAttribute('registration_time', object(Carbon)) in Model.php line 422
AuthController.php (controller)
$registration = Registration::create([
'business_id' => '1',
'registration_time' => \Carbon\Carbon::today()->addDays(3)->addHours(10)->toDateTimeString()
]);
Echo of registration_time in controller
2016-02-12 10:00:00
Registration.php (model) line 111
public function setRegistrationTimeAttribute($registration_time)
{
$this->attributes['registration_time'] = Carbon::createFromFormat('Y-m-d H:i', $registration_time, \Auth::user()->timezone)->setTimezone('UTC');
}
What I don't understand, is that similar code works in my RegistrationTableSeeder, my model accepts this format.
'registration_time' => \Carbon\Carbon::now()->addDays(3)->addHours(1)->toDateTimeString(),

RequestException in CurlFactory.php line 187

I'm using Laravel 5.1 and want to send email but I'm getting this error:
RequestException in CurlFactory.php line 187:
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
How could I solve this?
My .env file:
MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_USERNAME=myemail#gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=oEontENjBIdIrzaXhk9v9Q
My function in controller:
public function mailContact(ContactRequest $request)
{
$name = $request->input('name');
$email = $request->input('email');
$body = $request->input('body');
$sent = Mail::send('emails.contact', compact('name', 'email', 'body'), function ($message) {
$message->to('khudadadrs#gmail.com', 'Admin')->subject('Message');
});
if ($sent) {
return Redirect::back()->withMessage('تشکر از اینکه تماس گرفتید.');
}
return Redirect::back()->withError('متاسفانه ایمیل ارسال نشد.دوباره تلاش کنید');
}
Download the https://gist.github.com/VersatilityWerks/5719158/download
Extract it an place it in ..\php\ext (curl.cainfo="E:\xampp\php\ext)"
Open the php.ini and write after the php_curl.dll: curl.cainfo="..\php\ext\cacert.pem"(curl.cainfo="E:\xampp\php\ext\cacert.pem")
Restart the web server.
I added the cacert.pem file as described in http://codeontrack.com/solve-laravelxamppguzzlehttp-curl-error-60-no-sll-certificate/
but now I'm getting this error:
RequestException in CurlFactory.php line 187:
cURL error 77: error setting certificate verify locations:
CAfile: [pathtothisfile]\cacert.pem
CApath: none (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
Any help?

Resources