I am trying to update a query every day using the laravel task scheduler. I currently have a home controller in which I select the picture with the most likes and pass the result to my home page. I also have started a windows task which calls my laravel schedule every minute.
HomeController:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->orderBy('likes_count', 'desc')
->with('user')
->first();
$drinkOfTheDay = Picture::withCount('likes')
->where('picture_type', 'drink')
->orderBy('likes_count', 'desc')
->with('user')
->first();
return view('timeline.index', [
'users' => $users,
'pictures' => $pictures,
'comments' => $comments,
'foodOfTheDay' => $foodOfTheDay,
'drinkOfTheDay' => $drinkOfTheDay,
]);
Schedule:
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->call('\App\Http\Controllers\HomeController@petsOfDay')->daily();
}
I'm wondering how I could update the food and drink of the day variables from my schedule all the while keeping them accessible to my home view.
Thank you for your help.
First, you need to create a command with php artisan make:command YourCommandName
. This creates a file in app/Console/Commands/
.
In the newly created Command file, change then $signature
to something useful. Also, in the handle()
method, write your logic there.
Next, you have to register the command in $commands
array in app/Console/Kernel.php
.
Finally, in the schedule()
method of app/Console/Kernel.php
, call your command with frequency e.g $schedule->call('command:signature')->daily();
PS: This assumes you already have a corn job set up on your server that runs every minute.
To solve the problem, create a new database table that stores the pictures of the day. Then, create an artisan command which uploads the food and drink variables. In a schedule, update the artisan command daily. Lastly, write a query in the controller that selects the most recent result from the picture of the day table for each category and pass the result of that query to the view.