Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lugi's avatar
Level 21

Inheritance and fetching all objects to their real type

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
0 likes
1 reply

Please or to participate in this conversation.