How can I add, delete and get a favorite from product with polymorphic relationship, in Laravel 5.6?
Asked Answered
B

0

2

My product model like this :

<?php
...
class Product extends Model
{
    ...
    protected  $fillable = ['name','photo','description',...];
    public function favorites(){
        return $this->morphMany(Favorite::class, 'favoritable');
    }
}

My favorite model like this :

<?php
...
class Favorite extends Model
{
    ...
    protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
    public function favoritable()
    {
        return $this->morphTo();
    }
}

My eloquent query laravel to add, delete and get like this :

public function addWishlist($product_id)
{
    $result = Favorite::create([
        'user_id'           => auth()->user()->id,
        'favoritable_id'    => $product_id,
        'favoritable_type'  => 'App\Models\Product',
        'created_at'        => Carbon::now()
    ]);
    return $result;
}
public function deleteWishlist($product_id)
{
    $result = Favorite::where('user_id', auth()->user()->id)
                      ->where('favoritable_id', $product_id)
                      ->delete();
    return $result;
}
public function getWishlist($product_id)
{
    $result = Favorite::where('user_id', auth()->user()->id)
                      ->where('favoritable_id', $product_id)
                      ->get();
    return $result;
}

From the code above, I'm using parameter product_id to add, delete and get data favorite

What I want to ask here is : Whether the above is the correct way to add, delete and get data using polymorphic relationship?

Or is there a better way to do that?

Beard answered 27/3, 2018 at 12:32 Comment(5)
If the code works and you want a review or how you can improve it, you should ask at codereview.stackexchange.comNotability
if the only favoritable_type is product, then it is no need to use polymorphic relationshipSouthernly
@Southernly I think it can add, delete and get data using polymorphic relationshipBeard
Did you get your answer?Cranial
@João Mantovani Not yet. I still use the above way for my caseBeard

© 2022 - 2024 — McMap. All rights reserved.