Programatically create record?

I need to create a record programatically every X hours for an admin to review and change status. I'm guessing I can run a cron job to do it but I haven't been able to find anything related to programatically create the record. Does anybody know if this can be done?
3 Replies
cheesegrits
cheesegrits9mo ago
Not really a Filament thing, it's 100% vanilla Laravel. Just schedule a queued job, and create your model. In app/Console/Kernel.php ...
protected function schedule(Schedule $schedule)
{
if (App::environment(['production', 'staging'])) {
$schedule->job(new YourJob)->hourly();
}
}
protected function schedule(Schedule $schedule)
{
if (App::environment(['production', 'staging'])) {
$schedule->job(new YourJob)->hourly();
}
}
... and in app/Jobs/YourJob.php ...
<?php

namespace App\Jobs;

use App\Models\YourModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class YourJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct()
{
}

public function handle(): void
{
YourModel::create([
'foo' => 'bar',
//
]);
}
}
<?php

namespace App\Jobs;

use App\Models\YourModel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class YourJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public function __construct()
{
}

public function handle(): void
{
YourModel::create([
'foo' => 'bar',
//
]);
}
}
https://laravel.com/docs/10.x/scheduling#scheduling-queued-jobs
Laravel - The PHP Framework For Web Artisans
Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.
El Bolo
El Bolo9mo ago
Sorry, I'm fairly new to Laravel so I didn't even think of this way but it makes a lot of sense! Thanks a lot 🙏
cheesegrits
cheesegrits9mo ago
Note that you would very probably want to be using queues to do this, so you'll need to read up on queue handling. Easiest way of managing queues is with Horizon. What do you host your app on?