Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

morphTo and hasMany Laravel

Tags:

php

mysql

laravel

A quick query regarding some data model relations in Laravel.

I have a product, that belongs to a user, but a user can have many products. But a product can also have many people making an offer on that product so;

class Product extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }
    public function offer(){
        return $this->hasMany('App\Offer');
    }

But a product can also have different sub types of product, for example, one might be a vehicle, or a mobile phone, each with different columns in my migration, so I assume I need morph many

In Product.php

public function imageable()
{
    return $this->morphTo();
}

In Vehicle.php

public function products()
{
  return $this->morphMany('App\Product', 'imageable');
}

However, when calling:

$product = Product::findOrFail($id);

I get null when I attempt do anything like $product->vehicle

I add the ID of the vehicle in my database to the imageable_id on the products table, and the imageable type to 'vehicle' on the products table too.

What am I doing wrong here?

like image 721
iLC Avatar asked May 10 '17 15:05

iLC


1 Answers

Everything looks right you just should be accessing it via imageable:

$product = Product::findOrFail($id);
return $product->imageable;

From the Laravel documentation:

You may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphTo.

In your case the method that performs the call to morphTo is imageable.

like image 168
Alex Harris Avatar answered Oct 29 '22 13:10

Alex Harris