Filipe Ferminiano Filipe Ferminiano - 1 month ago 6
PHP Question

Trying to get property of non-object with Model Relationship

I'm trying to get a relationship between models in a laravel template.
I want to get the product fields respective to an ad.

This is my AdController:

public function ads(Request $request)
{
$this->adRepository->pushCriteria(new RequestCriteria($request));
$hash = Auth::user()->environment_hash;
$ads = $this->adRepository->findByHash($hash);
return view('ads.index')
->with('ads', $ads);
}


This how I'm parsing to my blade template:

@foreach($ads as $ad)
<tr>
<td>{!! $ad->product->name !!}</td>
</tr>
@endforeach


But I keep getting this error:

Trying to get property of non-object


This is the adRepository file:

public function findByHash($hash = null)
{
$model = $this->model;

if($hash)
$this->model->where('environment_hash', $hash);
else
$this->model->where('environment_hash', Auth::user()->environment_hash);

return $model;
}


This my Ad Model: Ad.php

<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Ad extends Model
{

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


This is my ad table:

id
product_id
environment_hash


And my product table:

id
environment_hash
name


What is wrong with the code?

Answer

Not sure but there must be some ad which has no product in your database. So this may be the reason you are getting error. Make sure that all of your ad has related product in database.

You can test it by running following code:

 @foreach($ads as $ad) <tr> <td>Test  {!! $ad->product !!}</td> </tr> @endforeach

If you get result like this:

  Test some_name
  Test
  Test some_another_name

Then this is confirm that some ad has no related product.

If this is the case then you need to if() check before accessing the attributes of product.

Update

The problem is that you are missing get() in your findByHash(). It should be as:

public function findByHash($hash = null)
{
    $model = $this->model;

    if($hash)
        $this->model->where('environment_hash',  $hash);
    else
        $this->model->where('environment_hash',  Auth::user()->environment_hash);

    return $model->get();
}