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

noblemfd's avatar

How to run cron jobs for multiple companies

I have this code in Laravel-5.8 cron jobs:

public function handle()
{
    $linemanager = User::distinct()->where('company_id', 1)->whereNotNull('line_manager_id')->pluck('line_manager_id');
    $users = User::whereIn('employee_code', $linemanager)->where('company_id', 1)->get();
    foreach ($users as $user) {
        if (! $user->hasRole('Line Manager')) {
           $user->assignRole('Line Manager');  
        }
    }        
 } 

Initially I have just one company. Each user table have company_id, that's why company_id is 1. I use the user table to Assign Line manager role (Spatie RBAC). I did this in the cron jobs. I have multiple companies with user table still having company_id.

How do I now re-write the cron jobs (Since I have multiple companies now and can't determine which is 1 and so on) to assign Line Manager roles to the users?

Thanks

0 likes
4 replies
noblemfd's avatar

@snapey - Thanks for your politeness. So sorry I didn't make it clear enough. What I mean is that without stating stating that company_id is 1 or 2 or 3,, like this, where('company_id', 1). How do I Assign Line Manager Roles to the user based on their company?

Thanks

automica's avatar

If you’ve got a list of companies that you want to a specific task for, there’s a number of ways.

Probably easiest to add a new crontab for each company and set the company_id as an argument

if you want just one crontab, for each through a list of companies and then add your current handle method inside the loop.

Depending on how long it takes to run the task, you could trigger and queue an event inside the foreach which would mean if one failed it wouldn’t kill the whole update.

Snapey's avatar

You want to assign a role to someone every minute?

Why is this in a scheduled task?

Please or to participate in this conversation.