Laravel eloquent don't get relation model many to many relation

143 Views Asked by At

[][1]we can retrieve the Post model for a Comment by accessing the post "dynamic property I have a Posts table My Order Model

class Order extends Model
{
    protected $table = 'orders';

    protected $fillable = ['user_id', 'billing_phone', 'billing_address', 
                           'payment_method', 'payment_status', 'product_id', 'order_status'];

    }
    public function products()
    {
        return $this->belongsToMany(Product::class, 'order_product', 'order_id', 'product_id');
    }

}

My web route

Route::get('get-orders', function() {

    $orders = \App\Models\Order::all();
    foreach ($orders as $order) {
        
        foreach ($order->products as $product) {
            echo 'ID: ' . $product->name;
        }
    }
});

Now I want to get orders & its products, what is the problem?

When i due and dump this is the retun result [1]: https://i.stack.imgur.com/IaqEv.png

1

There are 1 best solutions below

2
On

Try this with better performance.

Order.php model:

class Order extends Model
{
    protected $table = 'orders';

    protected $fillable = [
        'user_id',
        'billing_phone',
        'billing_address', 
        'payment_method',
        'payment_status',
        'product_id',
        'order_status'
    ];
   
    public function products()
    {
        return $this->belongsToMany(
            Product::class,
            'order_product',
            'order_id',
            'product_id'
        );
    }
}

web.php route file:

Route::get('get-orders', function() {

    //use eager load here, better performance.
    $orders = \App\Models\Order::with('products')->get();

    foreach ($orders as $order) {
        foreach ($order->products as $product) {
            echo 'ID: ' . $product->name;
        }
    }
});