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

afrayedknot's avatar

Handling Polymorphic Tables

Lets say I have a Booking table.

   Class Booking extends BaseModel { 
   public function bookable()
    {
        return $this->morphTo();
    }
   }

I have a polymorphic relationship - so I can have different types of Bookings.

i.e. CarBooking, BoatBooking, TrainBooking

  class CarBooking extends BaseModel {
    public function booking()
    {
        return $this->morphOne('Booking', 'bookable');
    }
  }

How do I write a BookingController that can be passed any implementation of a Booking and handle it?

i.e. at the moment I've written a CarController, BoatController, TrainController. I want to make them one controller, since the code is almost identical apart from the injection of the initial class.

Is there a Laracasts video on this topic?

0 likes
1 reply
JarekTkaczyk's avatar

Isn't it misconception? From what you say it seems that you need polymorphism of the classes, not polymorphic relations.

If Car/Train/WhateverBooking can be swapped, then simply create different classes extending one common Booking. Why do you need separate tables? (Or you don't?)

Please or to participate in this conversation.