I have a one-to-many relationship in my code that I want to show on my view, but I get a NULL
error. Below is the model with the defined relationship.
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
This is my controller method:
$products = Invoice::with('products')->get();
return view('admin.invoices.show',
compact('invoice', $invoice),
compact('clients', $clients))->with(compact('products', $products));
This is my view, but it always displays no products:
@foreach ($products as $product)
<td>{{ $product->product->name ?? 'no products' }}</td>
@endforeach
When I dd()
the $products
array, I get the following:
#relations: array:1 [▼
"products" => Collection {#321 ▼
#items: array:1 [▼
0 => Product {#318 ▼
#fillable: array:5 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:8 [▼
"id" => 1
"name" => "asd"
EDIT
here is my full controller that i get the relation with users with no problem thats a hasOne relation but i cant access the products relation and that s main problem
public function show(Invoice $invoice)
{
$clients = Invoice::with('user')->get();
$products = Invoice::with('products')->get();
return view('admin.invoices.show', compact('invoice', $invoice),compact('clients',$clients))->with(compact('products',$products));
}