Afzal Hussain Shuhag
Afzal Hussain Shuhag

Reputation: 11

How to solve this in Laravel 6? Trying to get property 'name' of non-object

My Model

class Purchase extends Model
{
  public function supplier()
  {
    return $this->belongsTo(Supplier::class,'supplier_id','id');
  }

  public function unit()
  {
    return $this->belongsTo(Unit::class,'unit_id','id');
  }

  public function category()
  {
    return $this->belongsTo(Category::class,'category_id','id');
  }

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

My Controller

class PurchaseController extends Controller
{
  public function view()
  {
    $data['allData'] = Purchase::orderBy('id','desc')->get();
    return view('backend.purchase.view-purchases', $data);
  }

My View Page

@foreach($allData as $key => $purchase)
    <tr>
      <td>{{ $loop->index + 1 }}</td>
      <td>{{ $purchase->purchase_no }}</td>
      <td>{{ $purchase->product->name }}</td>
      <td>{{ $purchase->unit->name }}</td>
      <td>{{ $purchase->date }}</td>
      and 2 more td for edit and delete
@endforeach

But there's still errors in all {{ $purchase-> example}}. I can't find the errors. If I check the dd() method right after the tr tag it works but it doesn't get the {{ $purchase-> example }}. I have the following error message:

Trying to get property 'name' of non-object (View: C:\xampp\htdocs\POS\resources\views\backend\purchase\view-purchases.blade.php).

enter image description here

Upvotes: 1

Views: 134

Answers (1)

Abu
Abu

Reputation: 226

Try loading the relations in the controller e.g.

$data['allData'] = Purchase::with('supplier', 'unit', 'category', 'product')->orderBy('id','desc')->get();

I would also advise you to change your controller view method body to the following.

$purchases = Purchase::with('supplier', 'unit', 'category', 'product')->orderBy('id','desc')->get();
return view('backend.purchase.view-purchases')->with(['purchases' => $purchases]);

So then in your view try to access it like the following.

@foreach($purchases as $purchase)
...
<td>{{ $purchase->purchase_no }}</td>
...
@endforeach

Upvotes: 1

Related Questions