That way you will never learn to properly delegate responsibilities. Better create a class that will do the work that which can use in your Nova action and Job.
Call a Laravel Nova action in a job
Hey, I am trying to call a action from job, in order to not repeat code. This action has 1 field so I would need to pass that too. This is how I am trying:
$collection = $this->model;
$action = new MyAction;
$request = app(ActionRequest::class);
$request->action = $action->uriKey();
$fields = $request->resolveFields($request);
DispatchAction::forModels($request, $action, 'handle', $collection, $fields);
but I get
Unresolvable dependency resolving [Parameter #0 [ <required> $resource ]] in class Laravel\Nova\Resource
Any idea how to get this working and how could I pass a field into the action? Thanks in advance to anyone that helps.
@bellini not quite.
public function handle(ActionFields $fields, Collection $users)
{
foreach ($users as $user) {
$user->subscribe();
$user->notify(new InvoicePaid($user->lastInvoice));
$user->notify(new ActivationSMS);
// and so on...
}
}
You can change it to:
public function handle(ActionFields $fields, Collection $users)
{
foreach ($users as $user) {
(new SubscribeAndNotifyUser($user))->handle();
}
}
class SubscribeAndNotifyUser
{
public function __construct(User $user)
{
$this->user = $user;
}
public function handle(): void
{
$this->user->subscribe();
$this->user->notify(new InvoicePaid($user->lastInvoice));
$this->user->notify(new ActivationSMS);
// and so on...
}
}
Now you can use that class in your Job class and you don't have to repeat anything or do the hard work of figuring out how to pass action fields since that class can change and when you upgrade Nova it can break your code.
Also, as a side note, you do know that you can queue Nova actions by adding implements ShouldQueue to your action?
Please or to participate in this conversation.