Language:

Search

One to Many Polymorphic Relation in Laravel

  • Share this:
One to Many Polymorphic Relation in Laravel

Laravel Eloquent is the ORM (Object-Relational Mapping) implementation included in the Laravel PHP framework. It provides a simple and elegant way to interact with databases using an object-oriented syntax.

Also Read: Laravel Livewire comments

Introduction to Laravel Polymorphic Relations

A Polymorphic relationship in Laravel allows the child model to belong to more than one type of model using a single association.In other words, a single model can be related to multiple models on a single relationship.

Also Read: Secure Laravel app before moving to production

Here's an example of a polymorphic One to Many relationship in Laravel, which is most commonly used in our projects too.

// Define the Image model
class Image extends Model
{
    public function imageable()
    {
        return $this->morphTo();
    }
}
// Define the Product model
class Product extends Model
{
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}
// Define the User model
class User extends Model
{
    public function images()
    {
        return $this->morphMany(Image::class, 'imageable');
    }
}

In this example, the Image model can be related to either a Product or a User model. This is accomplished by defining a morphTo relationship in the Image model and a morphMany relationship in both the Product and User models. This type of relationship can be useful when you have a model that needs to be associated with multiple other models, but you don't want to create separate relationships for each model.

Also Read: Laravel Deployments using Envoy

Now in order to retrieve the images from User Model and Product Model

//user model and get images
$user = App\Models\User::find(1);
 
foreach ($user->images as $image) {
    //do something with the image now.
}
//product model and get images
$product = App\Models\Product::find(1);
 
foreach ($product->images as $image) {
    //do something with the image now.
}
TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques