I have builded a system in larvel and vue js, so i have some users who can have access on this system. Now i need for each user they to see only data belongs to his team where hi is on this team. I have some workers, teams, and jobs. When a worker is created, a user is also created in the users table. the user that is created takes a field called worker_id that corresponds to the id of the worker that is created. Now this worker is in a team, and several jobs have been assigned to this team. I want that when this user who has the same worker_id with worker->id logs in, he can only see the jobs assigned to his team.
jobcontroller function to show jobs
$jobs = Job::with(['teams', 'clients'])
->whereHas('teams', function ($q) {
return $q->where('id', auth()->user()->worker_id); //i know there is wrong, iam just trying
})
->orderBy('id', 'DESC')->paginate($paginate);
return JobResource::collection($jobs);
jobrelationships
public function teams()
{
return $this->belongsToMany(Team::class);
}
public function clients()
{
return $this->belongsToMany(Client::class);
}
teamrelationship
public function jobs()
{
return $this->belongsToMany(Job::class);
}
workerrelationsip
public function teams()
{
return $this->hasOne(Team::class);
}
CodePudding user response:
In your example you are attempting to query for teams by using the worker ID, rather than querying for teams using the worker's team ID.
$workerId = auth()->user()->id;
$jobs = Job::with('teams.workers')
->whereHas('teams.workers', function ($q) { return $q->where('id', $workerId); })
->orderBy('id', 'DESC')
->paginate(10);
return JobResource::collection($jobs);