Is it necessary to have 2 separate models for your users? It might be easier to have 1 user table with a usertype field which you could set to either student or professor.
Record Ownership (with multiple owners types)
Let me explain that better with a practical example.
Imagine you have a typical User model and there's two types of users (Professors & Students).
Then another model can be Book and in this table there are the following fields: id, professor_id,student_id etc..
In the User model the relationships are:
public function books()
{
return $this->hasMany('App\Book', 'student_id');
}
Is that correct? Can I do the same for professor_id?
And to finish this how can I check the resource ownership, so only students can see their books and the professors can see, edit etc their books as well?
Can anyone point me in some direction? Any tutorial, video, book?
As you can see I'm kinda lost here :)
PS: Both users can login ofc.
@hfalucas @Graham There is no place for m-m relationship here. It's simple hasMany. There's only one thing that you didn't describe - how do you differentiate Professor from Student if they use the same model?
Anyway, that's not important in this case, because all you need is this (assuming you want to track who created the book author_id and who is the book assigned to owner_id - such names are more readable for the sake of example, you may use student_id and professor_id):
// User model
public function booksCreated()
{
return $this->hasMany(Book::class, 'author_id');
}
public function booksOwned()
{
return $this->hasMany(Book::class, 'owner_id');
}
// Book model
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
public function owner()
{
return $this->belongsTo(User::class, 'owner_id');
}
And you use the relationship you need depending on the user type, that's all.
Please or to participate in this conversation.