From SalesController
, I want to get specific name
from table Item
and passed to HTML.
My controller looks like
public function index() { $items=Item::orderBy('name','ASC')->get()->pluck('name','id'); $sales=Sale::all(); return view('Sale.index')->with('sales',$sales,'items',$items); }
My HTML is
<thead> <tr> <th>No</th> <th>Name</th> <th>Quantity</th> <th>Total Price</th> <th>Detail</th> </tr> </thead> <tbody> @foreach($sales as $sale) <tr> <td>{{ $sale->id }}</td> <td>{{ $sale->items->name }}</td> <td>{{ $sale->quantity }}</td> <td>RM {{ $sale->price }}</td> <td>{{ $sale->created_at }}</td> </tr> @endforeach </tbody>
But I get the following error after trying to access the page:
Trying to get property ‘name’ of non-object (View: C:xampphtdocsinventoryAppresourcesviewsSaleindex.blade.php)
Advertisement
Answer
there are two way
1.Using relationship
class Sale extends Model { public function item() { return $this->belongsTo('AppItem','item_id','id'); } }
so you can use like below
<td>{{ $sale->item->name }}</td>
2. Using array data
public function index() { $items=Item::orderBy('name','ASC')->pluck('name','id')->toArray(); $sales=Sale::all(); return view('Sale.index')->with('sales',$sales,'items',$items); } <td>{{ $items[$sale->item_id] }}</td>