Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : load objects on many level

Tags:

php

laravel

I have the following tables :

orders : id, etc...

order_lines : id, order_id, product_id, etc...

products : id, name, etc...

Foreign keys are defined.

My Laravel Models are defined as :

class Order

 public function orderLine()
    {
        return $this->hasMany('App\OrderLine');
    }
class OrderLine

public function order()
    {
        return $this->belongsTo('App\Order');
    }

    public function product()
    {
        return $this->belongsTo('App\Product');
    }
class Product

public function orderLine()
    {
        return $this->hasMany('App\OrderLine');
    }

I've tried many things, but nothing is working. Here is the best solution for me, but it's not working.

class OrderController

public function show($id)
    {
        $user = Auth::user();
        $order = Order::where('user_id', '=', $user->id)->with(['orderLine.product'])->findOrFail($id);
        return view('layouts/order/index', compact('order'));
    }

I struggle to display the following data in the view :

@foreach($order->orderLine as $key => $orderLine)
<tr>
    <td>{{$orderLine->product->name}}</td>
<tr>
@endforeach

Product object is not loaded. I want to display the product name in the above loop.

like image 396
Dezaley Avatar asked Jul 09 '26 22:07

Dezaley


1 Answers

Try to do like this:

public function show($id)
    {
        $user = Auth::user();
        $order = Order::with(['orderLines', 'orderLines.product'])
                      ->where('user_id', '=', $user->id)
                      ->findOrFail($id);
        return view('layouts/order/index', compact('order'));
    }
class OrderLine

public function order()
    {
        return $this->belongsTo(\App\Order::class, 'order_id');
    }

    public function product()
    {
        return $this->belongsTo(\App\Product::class, 'product_id');
    }
class Order

 public function orderLines()
    {
        return $this->hasMany(\App\OrderLine::class);
    }

Change name of orderLine to orderLines because order has many orderLines.

And in your blade:

@foreach($order->orderLines as $orderLine)
<tr>
    <td>{{$orderLine['product']->title}}</td> 
<tr>
@endforeach
like image 167
mare96 Avatar answered Jul 11 '26 13:07

mare96



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!