INTSIK PUDGE
INTSIK PUDGE

Reputation: 1

How to get the ID from this function and match it to my other table to get the Product_name (laravel)

public function viewCustomerOrders(){
    $orders = Order::with('ordersz')->get();

    return view('admin.orders.view_customers_order')->with(compact('orders'));
}

my public function code

<?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Order extends Model
    {
        public function ordersz(){
            return $this->hasMany('App\OrderProduct','order_id');
        }
        function product() {
            return $this->hasOne('App\Product');
        }
    }

my relation on my Order Model

Is it possible to do this one?

foreach($orders->ordersz as $try){
    $getTheProductIDfromOrdersTabel= $try->product_id;
    matchItTomyProductTableTogetName= Product::where('id',$getTheProductIDfromOrdersTabel)->get();
}

Because i have the orders table, and order_products table, and inside it is i have the order_id and product_id, i want to get the product_id from my condition and match it on my products table to display their product_names.

Upvotes: 0

Views: 42

Answers (1)

Brian Lee
Brian Lee

Reputation: 18197

What you're describing is a many-to-many relationship. In order to include all the requisite data you'll use eager loading.

Consider three tables - orders, products, and order_product. The respective models would be defined like:

Order

class Order extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
}

Product

class Product extends Model
{
    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }
}

The pivot table - order_product - would be only need two columns: order_id and product_id.

Now your controller method can be updated as:

public function viewCustomerOrders()
{
    return view('admin.orders.view_customers_order')->with([
        'orders' => Order::with('products')->get()
    ]);
}

Finally, to display the information in your view file, use @foreach:

@foreach($orders as $order)
    Order ID: {{ $order->id }}
    @foreach($order->products as $product)
        Product Name: {{ $product->name }}
    @endforeach
@endforeach

Upvotes: 0

Related Questions