Laravel filtering query results with relations

I have this relations
and defined models for all 3 tables

class Employee extends Model
{
    use HasFactory;
    protected $table = 'employees';
    public function departments()
    {
        return $this->belongsToMany(Department::class, 'dept_emp', 'emp_no', 'dept_no', 'emp_no', 'dept_no');
    }
}
class Department extends Model
{
    use HasFactory;
    protected $table = 'departments';

}
class Dept_emp extends Model
{
    use HasFactory;
    protected $table = 'dept_emp';
}

And in my controller
 $employees = Employee::with('departments')->paginate(50);

I want to filter this query result to be able to select only one chosen department and not all of them.

I tried adding to employee model this function

    public function scopeDepartment($query, $department)
    {
        return $query->where('dept_no',$department);
    }

but it isn’t working. Can someone advice me how to filter query results with relations?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

you can query within with relation as like

$employees = Employee::with(['departments' => function($q) use ($dept_id){
  $q->where('dept_no',$dept_id);
}])->paginate(50);

$dept_id is the id of department i.e $dept_id = $request->department_id something like


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x