Level 54
Sounds like you want to use single table inheritance. This might be useful: http://laravel.io/forum/02-17-2014-eloquent-single-table-inheritance
It's a bit old, but might get you pointed in the right direction
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have several types of User which are all stored in one DB table (single table inheritance).
When I fetch them with paginate() or all() they are always type of User.
Is there a way to get them in their real type ?
Here is an code example. With this code I will get this as an output in view:
WRONG:
I am user
I am user
I am user
...
I would like to get different responses depending on the type of user. For example:
CORRECT:
I am student
I am user
I am student
I am guest
...
class User extends Model {
// ...
public function presentItself() { return "I am user."; }
}
class Student extends User {
// ...
public function presentItself() { return "I am student."; }
}
class Teacher extends User {
// ...
public function presentItself() { return "I am teacher."; }
}
class Guest extends User {
// ...
public function presentItself() { return "I am guest."; }
}
CONTROLLER:
public function showAllUsers()
{
$users = User::all();
return view('users.index', compact('users'));
}
public function showSomeUsers()
{
$users = User::where('status', '=', 'active')
->latest('date_of_birth')
->paginate(10);
return view('users.someusers', compact('users'));
}
VIEW:
@foreach ($users as $u)
<li>{{ $u->presentItself() }}</li>
@endforeach
Please or to participate in this conversation.