mercredi 11 avril 2018

Laravel - Polymorphic relation, Trying to get property of non-object

I have a project where I am working with polymorphic relations. I've never worked with them so while I was experimenting with it, I came across an error while trying to get a value that was related to an object. My database consists of the following tables: Products, Themes, Plugins and Plans. It is build like this

Products
    - id
    - productable_type
    - productable_id
    - name
    - description
    - etc...

Themes
    - id
    - composer_package

And the other two (Plugin and Plan) are the same as theme

In my view, I'm trying to get the composer_package that is related to the selected product that the user want's to edit. So say for instance I want to edit the product with the ID of 21. I want to also be able to edit the composer_package with the ID of 21. But how can I retrieve the composer_package that is related to the selected product?

When I do $product->productable I retrieve a string with this info:

{"id":3,"composer_package":"composer_package3","created_at":"2018-04-11 07:38:03","updated_at":"2018-04-11 07:38:03"}

But I only need the field composer_package. I've tried doing $product->productable->composer_package but that gives me the error that is stated in the title.

I'm trying to do this in my view

 <div class="form-group mb-3">
   <label for="composer_package">Composer package</label>
   <input type="text" name="composer_package" class="form-control" value="">
 </div>

How can I achieve this?

Product model

This is the product model

/**
 * Polymoprhic relation
 */
public function productable()
{
    return $this->morphTo();
}

Theme model (It doesn't matter, Themes, Plans, Plugins models are all the same)

/**
 *
 */
public function products()
{
   return $this->morphMany(Product::class, 'productable');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire