I forgot to say that all user types share the tame departments.
Each user type can be part of any department.
But as I said, a person has just one user type and one department at the same time.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi all, I need your help!
Given I have some user types: teacher, students, workers and some departments: A, B, C.
One person is in one department and has one user type.
Now I want to create a blog post which all teachers from department A and students from B and C should see.
How do I setup and store and setup these relations?
I thought about a pivot table which holds the news_id, usertype_id and the department_id.
And to get all posts for a person maybe a call like this:
Post::teacher($department_id)->all()
But it would be great if I still could use the sync, detach, etc. methods to interact with the data.
Do you have any advice?
Just ask if you need more details :)
For all who have the same problem, that's my solution:
// Usertype Model
class Usertype extends \Eloquent {
//...
public function news()
{
$model = $this->belongsToMany('News', 'news_relations')->withPivot('department_id');
if($this->department_id) $model->wherePivot('department_id', '=', $this->department_id);
return $model;
}
}
// Department Model
class Department extends \Eloquent {
//...
public function usertypes()
{
return $this->belongsToMany('Usertype', 'news_relations')->withPivot('news_id');
}
public function news()
{
return $this->belongsToMany('News', 'news_relations')->withPivot('usertype_id');
}
}
// News Model
class News extends \Eloquent {
//...
public function departments()
{
return $this->belongsToMany('Department', 'news_relations')->withPivot('usertype_id');
}
}
Department::first()->news
Usertype::first()->news
Department::find(2)->usertypes()->find(2)->news
$relations = [
['department_id' => 2, 'usertype_id' => 2],
['department_id' => 1, 'usertype_id' => 2],
['department_id' => 3, 'usertype_id' => 3],
];
News::find(2)->departments()->sync($relations);
Please or to participate in this conversation.