1

I have this route call:

Route::resource('products', 'ProductController', ['except' => ['show']]);

So if I enter /products/438/edit it calls my edit method on controller, that is something like that:

 public function edit(Product $product){}

where $product is, correctly, my SELECT * FROM products WHERE id = 438

now my question is, what if I want to eager load a relation like prices()

I've tried:

$product = $product->with('prices');

and

$product = Product::find($product->id)->with('prices')

but without success. Thanks

Rocco Milluzzo
  • 997
  • 8
  • 16

2 Answers2

7

You can load relationships to an already existing model or collection using load():

$product->load('prices')

nxu
  • 2,202
  • 1
  • 22
  • 34
0

When you're doing Product $product and using resource controller, you're just injecting Product model. So, change function to:

public function edit(Product $product, $id)

You can eager load a relation with using of with() method:

$productData = $product->where('id', $id)->with('prices')->first();

Then you'll be able to access prices with something like this:

@foreach ($productData->prices as $price)
    {{ $price->sum }}
@endforeach
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Thanks for your support, It works of course, but what is the point o using injection if I'll have again to use something like $product->where('id', $id) ? I could just pass the $id and do a Product::find($id)->with('prices') if I wanted that. – Rocco Milluzzo Oct 27 '16 at 14:39
  • Dependency injection is just one of the many ways to use model class. When you pass an ID, you still need to get data from DB, because Laravel doesn't make this automatically. – Alexey Mezenin Oct 27 '16 at 14:51
  • When I pass just the ID I need to get data, when I inject, Product $product I don't. – Rocco Milluzzo Oct 27 '16 at 15:12
  • You don't get the data. You just get an instance of a model class. It's like you'd do `$product = \App\Product;`. That's not the data, it's just an instance of a class. – Alexey Mezenin Oct 27 '16 at 15:18
  • Sorry if I insist but it is a Laravel Feature, when I do something like that it gives me a collection with the result of SELECT * FROM products WHERE id = 438 so $product definitively has data. Look at this https://scotch.io/tutorials/cleaner-laravel-controllers-with-route-model-binding – Rocco Milluzzo Oct 27 '16 at 15:25