Unable to send emails in laravel 5 app - laravel-5

Hello I have a laravel 5 app which is working perfectly in local environment. But in production emails are not getting sent instead I get the exception below:
1/1 FatalErrorException in AstAnalyzer.php line 125:
Cannot instantiate interface PhpParser\Parser
Path to file: /vendor/jeremeamia/SuperClosure/src/Analyzer/AstAnalyzer.php line 125
I don't get it because right now I am testing same function in local and is working. Every other path of the app is working except this one.
Below is the function:
public function update_password(Request $request, $id)
{
$this->validate($request, [
'new_password' => 'required|confirmed|min:6',
'new_password_confirmation' => 'required',
]);
$user = $this->user->get_user_by_id($id);
$password = $request->get('new_password');
$this->user->save_password($password, $id);
// Send an email informing user that we have updated his password.
Mail::queue('emails.password_update', ['user' => $user, 'password' => $password], function($message) use ($user){
$message->to($user->email, $user->name)->subject('Account Password Updated');
});
$target_location = 'users/'. $id. '/profile';
flash()->success('Password Updated Successfully');
return redirect($target_location);
}

I finally solved my problem. I ran a composer update which installed the lastest version of nikic/php-parser and equally the latest version jeremeamia/superclosure, but somehow, the class Parser which was formally use in nickic's package was now an Interface. class Multiple was now implementing the interface. So in AstAnalyzer.php in jeremeamia's package, that change was not made and instead use PhpParser\Parser as CodeParser; was used which is logical as an interface cannot be instantiated unless some binding is done. So as a quick fix, I used the previous version of nikic/php-parser.

Related

Lumen : 1s, Laravel : 5s for a simple api call?

So I started a project not long ago for an API on Laravel, and I thought why not give Lumen a shot. But in the end, I want to use Sanctum, Socialite, etc... And I read pretty much everywhere that the performance difference is not that big nowadays anyway.
So I migrated my code from Lumen to Laravel, and after a few tweaks, everything works as before... Except that now a very simple API call takes 5s. Granted, it might be my setup - wsl2 isn't particularly fast. But still, the same call in Lumen was taking ~1000ms.
Route::post('register', [AuthController::class, 'register']);
Controller:
public function register(Request $request): JsonResponse {
$this->validate($request, [
'phone' => 'required|string|phone',
'phone_country' => 'required_with:phone',
]);
$phone = phone($request->get('phone'), [$request->get('phone_country')]);
try {
$user = User::createByPhone($phone);
return response()->json(['user' => $user->id, 'message' => 'SMS_SENT'], 201);
} catch (\Exception $e) {
return response()->json(['message' => 'User Registration Failed - ', 'error' => $e], 409);
}
}
Function in model:
public static function createByPhone($phone) {
return DB::transaction(function () use ($phone) {
$user = User::create();
$user->phoneNumbers()->create([
'did' => $phone
]);
return $user;
});
}
So, pretty simple stuff. Now, why is that taking so long? ~6000ms. Am I missing something?
(On a more general note, is there a way to cut from Laravel things that aren't needed for an API only?)
Thanks ahead.
I don't see anything really wrong with your code. I guess this has something to do with the speed wsl2 can read files. We had issues with windows machines and Laravel in Docker. We added Swoole to our project and this helped alot on WSL2.
Laravel now has a first party package called Octane to add Swoole to your project. You can try and install that to see if it helps.

Can't get user while testing auth in laravel

I'm writing automated tests for a legacy laravel project, 5.8.38.
I have this test method.
public function testUserReceivesAnEmailWithAPasswordResetLink()
{
Notification::fake();
$user = factory(User::class)->create([
'email' => 'john#example.com',
]);
$this->post($this->passwordEmailPostRoute(), [
'email' => 'john#example.com',
]);
$this->assertNull($token = DB::table('password_resets')->first());
Notification::assertSentTo($user, ResetPassword::class, function ($notification, $channels) use ($token) {
return Hash::check($notification->token, $token->token) === true;
});
}
This always fails because the user cannot be retrieved. The passwordEmailPostRoute() method goes to the src/Illuminate/Auth/Passwords/PasswordBroker.php sendResetLink() method, eventually ending up in src/Illuminate/Auth/EloquentUserProvider.php at retrieveByCredentials() method.
This always returns null.
I tried dumping data and queries, but everything failed. Any ideas appreciated.
This seems to be a very specific issue which I caused for myself.
My user factory generated wrong values for a morph connection field which prevented the return of a valid User object. I had to change the factory and the issue is now resolved.

Update Method in Laravel

I'm new to Laravel. I am using laravel 5.4 and trying to validate and update data in a model. Code looks like this:
Route
Route::resource ('contribution-structure', 'ContributionStructureController');
ContributionStructureController
public function update(Request $request, $id)
{
//
$data = $this->validate($request, [
'employer_name' => 'required|min:3',
]);
$plansubmission = PlanSubmission::find($id);
$plansubmission->update($data);
}
The validation works but when I update I get an error saying:
Argument 1 passed to Illuminate\Database\Eloquent\Model::update() must
be of the type array, null given, called in
C:\xampp\htdocs\tapp\app\Http\Controllers\ContributionStructureController.php
on line 84 and defined
The validator doesn't return anything in versions earlier than Laravel 5.5. To get your code to work I would recommend updated to that latest version. Especially for new projects, you should always start with the latest stable version.
If you don't want to update you need to pull the data from the request after validating.
public function update(Request $request, $id)
{
$this->validate($request, [
'employer_name' => 'required|min:3',
]);
$data = $request->only('employer_name');
$plansubmission = PlanSubmission::find($id);
$plansubmission->update($data);
}
Today i told about the update method in php framework laravel there is an error message gives when we apply update method in laravel
when we build the update method to update the data of the database table we face some issues for example
The controller does not fetch the id
The Route problem which route is good PUT, get, Post, Patch
and the laravel version problem
first the controller issue
public function Delivery_charges_update(Request $request, $id)
{
// return $request->all();
$request->validate([
'start-km' => 'required',
'end-km' => 'required',
'amount' => 'required',
]);
$data = Deliverycharges::find($id);
$data->start_km = $request->get('start-km');
$data->end_km = $request->get('end-km');
$data->amount = $request->get('amount');
$data->update();
return redirect('/SuperAdmin/Delivery_charges');
}
then second the route issue you can make route by post method because it is best
Route::post('/Delivery_charges_update/{id}', 'SettingController#Delivery_charges_update');
then third the laravel version issue
so the latest version of laravel is 5.5
and this all issues solution is valid for this laravel version

Lumen job dispatching done without database Queue Driver

What do I have:
Lumen service which processing particular Job
Laravel portal which sending file to that service for processing by it
Once it was using only JS and Ajax it worked almost fine - the only what I had to implement is CORS middleware. However after I moved logic to JWT (using jwt-auth package) and GuzzleHttp (I'm using it to send requests to service API) Job stopped processing throught database queue instead it running as if Queue driver being set to sync.
Following is controller which I'm calling during API call:
public function processPackageById(Request $request) {
$id = $request->package_id;
$package = FilePackage::where('id', '=', $id)->where('package_status_id', '=', 1)->first();
if($package) {
Queue::push(new PackageProcessingJob(
$this->firm,
$this->accounts,
$package
));
return 'dispatching done for ' . $id;
}
return 'dispatching not done for ' . $id;
}
where $this->firm and $this->accounts are injected Repositories for particular models. FilePackage object being created on Laravel site and both shares same database to work with.
As result no job being incerted into jobs table. When I use Postman everything is fine. However when I'm trying to send request from Laravel backend:
public function uploaderPost(Request $request)
{
// Here we get auth token and put into protected valiable `$this->token`
$this->authorizeApi();
$requestData = $request->except('_token');
$package = $requestData['file'];
$uploadPackageRequest =
$this->client->request('POST', config('bulk_api.url') .'/api/bulk/upload?token=' . $this->token,
[
'multipart' => [
[
'name' => 'file',
'contents' => fopen($package->getPathName(), 'r'),
'filename' => $package->getClientOriginalName(),
],
]
]);
$uploadPackageRequestJson = json_decode($uploadPackageRequest->getBody()->getContents());
$uploadPackageRequestStatus = $uploadPackageRequestJson->status;
if($uploadPackageRequestStatus == 1) {
$package = BulkUploadPackage::where('id', '=',$uploadPackageRequestJson->id)->first();
// If package is okay - running it
if($package !== null){
// Here where I expect job to be dispatched (code above)
$runPackageRequest =
$this->client->request('POST', config('api.url') .'/api/bulk/run?token=' . $this->token,
[
'multipart' => [
[
'name' => 'package_id',
'contents' => $package->id
],
]
]);
// Here I'm receiving stream for some reason
dd($runPackageRequest->getBody());
if($runPackageRequest->getStatusCode()==200){
return redirect(url('/success'));
}
}
}
return back();
}
Could anyone advise me what is wrong here and what causes the issue?
Thank you!
Alright, it was really interesting. After echoing config('queue.default') in my contoller it appeared that it's value indeed sync nevertheless that I set everything correctly.
Then I assumed that maybe the reason in Laravel itself and its variables. Indeed in .env file from Laravel side QUEUE_DRIVER being set to sync. After I changed it to QUEUE_DRIVER=database everything started working as expected.
Hope that will help someone in future.

Laravel 4 Mail function not working properly

I'm currently working on a web application which requires users to verify before they are able to use their account.
I'm using Cartalyst's Sentry to register the users, and sending the email using the built in Mail function, but whenever I register I get the following error:
Argument 1 passed to Illuminate\Mail\Mailer::__construct() must be an instance of
Illuminate\View\Environment, instance of Illuminate\View\Factory given,
called in
/var/www/vendor/laravel/framework/src/Illuminate/Mail/MailServiceProvider.php
on line 34 and defined
I can't figure out what causes this.
At the top of my code I included "use Mail" otherwise I would get another error:
Class '\Services\Account\Mail' not found
Code
// Create the user
$user = $this->sentry->register(array(
'email' => e($input['email']),
'password' => e($input['password'])
));
$activationCode = $user->getActivationCode();
$data = array(
'activation_code' => $activationCode,
'email' => e($input['email']),
'company_name' => e($input['partnerable_name'])
);
// Email the activation code to the user
Mail::send('emails.auth.activate', $data, function($message) use ($input)
{
$message->to(e($input['email']), e($input['partnerable_name']))
->subject('Activate your account');
});
Anybody got an idea what the solution for this error is?
Thanks in advance,
Kibo
Remove /bootstrap/compiled.php I think it will work for you.
You need to remove this from your Mail::send call. The function should be the third parameter so I'm not sure what you're trying to do here -- the $input['email'] field will already be available within the function due to your "use ($input)"
$email = e($input['email']

Resources