I have a fairly mature Laravel app that helps me manage my business. Recently I refactored the codebase to allow for multiple: projects and users.
//models/Project
public function users(){
return $this->belongsToMany(User::Class);//pivot table relationship
}
//models/User
public function projects(){
return $this->belongsToMany(Project::Class);//pivot table relationship
}
As such I placed a project_id field on most of my tables with the applicable foreign index.
I then applied the following scope to each of those tables...
class ProjectScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder
->where($model->getTable().'.project_id',
auth()->user()->settings['project_id']
);
}
}
Things worked great when performing operations as a logged in user.
Once running job queues the scoping gets all messed up as expected because a queued job has no awareness of: auth()->user()->settings['project_id']
I'm not sure what is the best way to scope queries to each project_id.
The only thing I can think of was to make a new table that would keep track of the current project_id "in focus" and to pass that id in with each job.
The query scope could check the DB field if the project_id === null.
Even as I type this it sounds like a horrible solution.
I'm sure there is some smart Laravel way to handle this...
What would you do to ensure all queued jobs stay scoped to each project?
Thanks.