Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saadaan's avatar

Setting cron for model related activities

Hi,

I have been reading material about how to set a cron in Laravel for scheduling tasks on some time frequency. However, almost all the examples are talking about some activity which is independent of any model or controller (does not engage any model or controller). For example: Sending emails to all users, or cleaning up database, etc. Both these commands are not using the active models in the application (sending email is triggering email app while database cleaning is using direct commands to database table to do something.

        $totalUsers = \DB::table('users')
                  ->whereRaw('Date(created_at) = CURDATE()')
                  ->count();
        Mail::to('[email protected]')->send(new SendMailable($totalUsers));

My requirement is different. I want to invoke a model (e.g. student), check his status at the start of the month (active, suspended, terminated), and post a stipend for him in another model (payment) table. This needs to be done for all the students which are active. This also involves logging user_id into different tables for doing the actions.

How do I do that?

Thanks, Saad

0 likes
6 replies
bugsysha's avatar
$students = Student::query()
	->correctStateScope()
	->get();

$students->each(fn (Student $student) => $student->doSomething());
saadaan's avatar

How do I handle the user_id, since the functions I am calling are based on user_id as well?

bugsysha's avatar

I have no idea what you are saying.

$students->each(function (Student $student) {
	$student->id; // is this what you are asking for?
	$student->doSomething();
});
saadaan's avatar

When some action is performed on the student model, the code is configured to capture the logged-in user_id and put it in the database as part of activity performer. This field is indexed to show list of activities of the users when they want to see which activities are performed by their login.

bugsysha's avatar

Then your system is not built properly or with CLI in mind.

Snapey's avatar

just use eloquent models (or DB) in your scheduled job as you would in a controller.

Dont use controller though as these are for handling http requests

You have no user, or rather the user is the command, you need to get your head around doing things from the perspective of the system

Please or to participate in this conversation.