Laravel 9 - RateLimiter unable to access protected property in Job - php

I have been trying to queue a job with Laravel 9 and setting a rate limit, to the API I am going to hit. The limit is max 10 requests per minute.
My AppServiceProvider.php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register() {}
public function boot()
{
RateLimiter::for('sendContentStackToEasyTranslate', function($job) {
return Limit::perMinute(10)->by($job->entry->id);
});
}
}
My middleware and constructor in SenCSToET.php job
namespace App\Jobs;
use App\Models\ContentStackEntry;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\RateLimited;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use IncrediblePony\Auditlog\Traits\AuditlogTrait;
class SendCSToET implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, AuditlogTrait;
/**
* #var \App\Models\ContentStackEntry
*/
protected $entry;
/**
* Create a new job instance.
*
* #param \App\Models\ContentStackEntry
* #return void
*/
public function __construct(ContentStackEntry $entry)
{
$this->entry = $entry;
}
/**
* Get the middleware the job should pass through.
*
* #return array
*/
public function middleware() {
return [new RateLimited('sendContentStackToEasyTranslate')];
}
}
https://laravel.com/docs/9.x/queues#rate-limiting is my source of this approach.
When the code is hit the error is presented to me:
{
"message": "Cannot access protected property App\\Jobs\\SendCSToET::$entry",
"exception": "Error",
"file": "/var/www/services/test-translation/releases/6/app/Providers/AppServiceProvider.php",
"line": 30,
}
BUT if I change the $entry variable in SendCSToET.php file from protected to public the code runs as expected. What am I missing?

It's a simple PHP behaviour, the callback from your RateLimiter does not belong to SendCSToET class or any subclass, so it can only access public properties/methods. So you have to choose between a public property or protected + public getter (cleaner way).
Example getter function in SendCSToEt.php:
protected $entry;
public function getEntry() {
return $this->entry;
}

Related

RateLimited middleware not working in Laravel 9 Job

I'm trying to send email notifications to my app users, limiting the number of emails to only 2 per minute, so as not to breach my email provider's allowed sending rate. So in MailingController.php I have:
<?php
namespace App\Http\Controllers;
use App\Jobs\SendMessages;
use Illuminate\Http\Request;
class MailingController extends Controller
{
public function send(Request $request) {
SendMessages::dispatch();
return redirect()->back()->withSuccess('Successful operation.');
}
}
SendMessages.php content is:
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Jobs\Middleware\RateLimited;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Redis;
class SendMessages implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 7200;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$users = User::all();
foreach ($users as $user) {
Log::debug('SendMessages#handle() ' . $user->email);
$user->notify(new VerifyEmail);
}
}
public function middleware()
{
return [new RateLimited];
}
}
And finally, RateLimited.php content is:
<?php
namespace App\Jobs\Middleware;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class RateLimited
{
/**
* Process the queued job.
*
* #param mixed $job
* #param callable $next
* #return mixed
*/
public function handle($job, $next)
{
Redis::throttle('key')
->block(0)->allow(1)->every(30)
->then(function () use ($job, $next) {
// Lock obtained...
Log::debug('RateLimited');
$next($job);
}, function () use ($job) {
// Could not obtain lock...
$job->release(16);
});
}
}
All these are copied and pasted from a Laravel 8 application that works perfectly fine, sending one email every 30 seconds as expected, but in my brand new Laravel 9 application the same code no longer works, and all email notifications are sent at once. I know I must be missing something, but have ran out of ideas. Any help would be greatly appreciated.
Thank you.

How can i pass a closure function to a laravel queue dispatch method

I want to pass a closure function to job dispatch method of Laravel queue. But i am getting "Serialization of 'Closure' is not allowed" exception. Can anyone please tell me how i can be able to pass closure function to the dispatch method?
Here are the controller codes:
public function syncProductByQueue($id){
$syncCallback=function() use($id){
$this->syncProduct($id);
};
ProcessSyncImport::dispatch($syncCallback);
}
And here is the job class:
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ProcessSyncImport implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
private $syncCallBack;
public function __construct($syncCallBack)
{
$this->syncCallBack= $syncCallBack;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$syncCallBack();
}
}

Emailing in Laravel

I am trying to send a email in Laravel. It works finicky to say at least. got couple of classes for sending email for different conditions. Only difference would be markup of sent email and blade file which data is sent to before sending. I tried using use Mail; in controller from whom i'm sending it, with \Mail::(... and use Illuminate\Support\Facades\Mail; with Mail::(... and vice-versa. So it ain't it.
Here are the mail files:
ToHR file:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\User;
class toHR extends Mailable
{
use Queueable, SerializesModels;
public $user;
public $job;
public $jobCount;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($user,$job,$jobCount)
{
$this->user = $user;
$this->job = $job;
$this->jobCount = $jobCount;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('mail.toHR');
}
}
ToHRFirst file:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\User;
class toHRFirst extends Mailable
{
use Queueable, SerializesModels;
public $user;
public $job;
public $jobCount;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($user,$job,$jobCount)
{
$this->user = $user;
$this->job = $job;
$this->jobCount = $jobCount;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('mail.toHRFirst');
}
}
And my test file JobCreated:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\User;
class JobCreated extends Mailable
{
use Queueable, SerializesModels;
public $user;
public $job;
public $jobCount;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($user,$job,$jobCount)
{
$this->user = $user;
$this->job = $job;
$this->jobCount = $jobCount;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->markdown('mail.job-created');
}
}
They'll all the same, yet error occurs. What gives? Did i miss something? Any help will be appreciated, just point me in the right direction.
Code which i use to send email:
Variables used get values from queries which are rather long, but they are not an issue anyways.
Ver1:
Mail::to($user->email)->send(
new JobCreated($user,$job,$jobCount)
);
Ver2:
Mail::to($user->email)->send(
new toHRFirst($user,$job,$jobCount)
);
Ver3:
Mail::to($user->email)->send(
new toHR($user,$job,$jobCount)
);
Sending works if it's used first version. Other cannot be found and that's the error.
Try renaming your files to follow Laravel convention;
You can see that the file JobCreated has a class JobCreated. You need to respect the uppercases:
Rename the ToHR.php file into ToHr.php, then:
Rename the class class toHRinto class ToHr
Rename the ToHRFirst.php file into ToHrfirst.php, then:
Rename the class class toHRFirst into class ToHrfirst
Or if you want to keep the uppercases, just rename the classes like so:
class toHRinto class ToHR
class toHRFirstinto class ToHRFirst
Finally, don't forget to import your job class at the top of your controller file (or wherever you use the Mail method:
use App\Mail\ToHR;
and
use App\Mail\ToHRFirst;

Sending Mails with Queues in Larvael

First time using queue in laravel i have a simple contact form page that user submit information and i am trying to use queue to receive that information. I am pretty sure that my setup is incorrect because when i run the queue it saying processing. My question is how come my data isn't sending and what the correct way of sending the data in the array.
AskEmailController.php
<?php
namespace App\Http\Controllers;
use App\Jobs\HelpEmailJob;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Request;
use Carbon\Carbon;
class AskEmailController extends Controller
{
public function askemail()
{
return view('help.question');
}
public function store(Request $request)
{
HelpEmailJob::dispatch()
->delay(Carbon::now()->addSeconds(5));
}
}
HelpEmailJob
namespace App\Jobs;
use App\Mail\HelpEmailMailable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class HelpEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Mail::to('mikeshasaco#gmail.com')->queue(new HelpEmailMailable());
}
}
HelpEmailMailiable
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class HelpEmailMailable extends Mailable
{
use Queueable, SerializesModels;
protected $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->$data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$data = array(
'sirname' => $this->data['sirname'],
'email' => $this->data['email'],
'bodymessage' => $this->data['bodymessage'],
);
return $this->view('help.contactinfo')
->with([
'data' =>$data,
]);
}
}
You can directly send the mail from your controller like this:
class AskEmailController extends Controller
{
public function store(Request $request)
{
Mail::to('mikeshasaco#gmail.com')->send(new HelpEmailMailable);
}
}
instead of using a job. And to make the email queue by default by implementing the ShouldQueue interface like this:
class HelpEmailMailable extends Mailable implements ShouldQueue
{
...
}
Make sure your queue is running when you test this and always restart it after you make a change in the code.

job class is not accepting the argument send from controller in laravel

Error: Missing argument 1 for App\Jobs\ReorderDatabase::handle() is showing,
I need to pass the variable from controller and i need not to use the model,
so How I should proceed.
My controller function code is here
public function postData(Request $request)
{
$updateRecordsArray = Input::get('order');
$this->dispatch(new ReorderDatabase($updateRecordsArray));
return Response::json('Okay');
}
My job RecorderDatabase job code is
<?php namespace App\Jobs;
use App\Http\Requests\Request;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\DragDropController;
/**
* Class ReorderDatabase
* #package App\Jobs
*/
class ReorderDatabase extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
}
/**
* Execute the job.
*
* #return void
*/
public function handle($updateRecordsArray)
{
$i = 1;
foreach ($updateRecordsArray as $recordID) {
DB::table('venues')->where('id', '=', $recordID)->update(array('priority' => $i));
$i++;
}
}
}
As #lagbox mentioned, you need to pass this argument into constructor and not handle method.
Your job class should look like this:
<?php namespace App\Jobs;
use App\Http\Requests\Request;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\DragDropController;
/**
* Class ReorderDatabase
* #package App\Jobs
*/
class ReorderDatabase extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $updateRecordsArray;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($updateRecordsArray)
{
$this->updateRecordsArray = $updateRecordsArray;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$i = 1;
foreach ($this->updateRecordsArray as $recordID) {
DB::table('venues')->where('id', '=', $recordID)->update(array('priority' => $i));
$i++;
}
}
}

Categories