I want to call a function in console.php as a schedule.
Here is my console.php code:
<?php
use AppHttpControllersAuctionController;
use IlluminateSupportFacadesSchedule;
Schedule::call(function () {
([AuctionController::class, 'endAuction']);
echo 'Zakończono aukcję.';
})->everyTenSeconds();
Here is my function code:
public function endAuction(Request $request, $id)
{
$auction = Auction::findOrFail($id);
DB::transaction(function () use ($auction) {
if ($auction->bids()->count() == 0) {
$maxQueue = Auction::max('queue');
$deletedQueueValue = $auction->queue;
$auction->update(['queue' => $maxQueue + 1]);
$this->rindexAuctionQueue($deletedQueueValue);
} else {
$auction->update(['status' => 'ended']);
if ($auction->currentBid) {
$auction->car->update([
'owner_id' => $auction->currentBid->user_id,
'status' => 'sold',
'price' => $auction->current_price
]);
}
$deletedQueueValue = $auction->queue;
$auction->delete();
$this->rindexAuctionQueue($deletedQueueValue);
}
});
return redirect()->route('mainpage')->with('success', 'Aukcja została zakończona.');
}
Scheduler works, theres a echo in terminal which is printing for every 10 seconds, but the function is not calling. Any help? THANKS!
2
Answers
it’s generally not best practice to call controller methods directly from a console command. Instead, it’s better to encapsulate your business logic within a service class. This way, you can easily reuse the logic in both your controller and console command.
Additionally, your endAuction function requires an ID and other context, we need to pass these appropriately.
Encapsulate the endAuction logic within a service class. Refactor the controller to use the service class and call the service class in your schedule.
The reason your controller function executing is because you never called it. The line
([AuctionController::class, 'endAuction']);
in your closure doesn’t call a function. All it does is create an array that looks something likeSo when your scheduled closure is called every ten seconds, it makes this array (doesn’t do anything with it), echo’s out the statement and exits.
As is mentioned in the comments, controller classes are used specifically for route logic. You’re better of making this into a console command, which can be scheduled easily. Then even if you did need to run this from a route, you can trigger the command progrommatically.
However, the quick and dirty way to get your code to run would to be to initiate the
AuctionController
class and call theendAuction
method on it. First you would need to refactor the function signature to no longer use the request. Then you could pass the ID as the first parameter.