Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get property of non-object - Laravel 5

I'm trying to echo out the name of the user in my article and I'm getting the

ErrorException: Trying to get property of non-object

My codes:

Models

1. News

    class News extends Model
    {
      public function postedBy()
      {
         return $this->belongsTo('App\User');
      }
      protected $table = 'news';
      protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
    }

2. User

    class User extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;

        protected $table = 'users';

        protected $fillable = ['name', 'email', 'password'];

        protected $hidden = ['password', 'remember_token'];

    }

Schema

table users

enter image description here

table news

enter image description here

Controller

public function showArticle($slug)
    {
        $article = News::where('slug', $slug)->firstOrFail();
        return view('article', compact('article'));
    }

Blade

{{ $article->postedBy->name }}

When I try to remove the name in the blade {{ $article->postedBy }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field namein my table and aUser` model. Am I missing something?

like image 398
wobsoriano Avatar asked Sep 09 '15 01:09

wobsoriano


People also ask

How do you handle Trying to get property of non objects?

Trying to get property of a non-object Errorforeach($po_items as $item){ if(is_null($item->vendor_company)){ continue } // do what you want with the vendor & vat_no. } A third option would be to query only the items that have a vendor company, assuming that there is a relationship involved in there.

What does Trying property of non objects mean?

The error occurs when you try to access a property of an object that isn't an object. In this case you cannot access the property, as the $result isn't an object. It is a boolean = false. One thing is to check that a variable is an object using PHP's is_object.


4 Answers

Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).

like image 141
Jimmy Zoto Avatar answered Nov 05 '22 23:11

Jimmy Zoto


I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:

First, as suggested by Jimmy Zoto, my code in blade from

$article->poster->name 

to

$article->poster['name']

Next is to add a second parameter in my belongsTo, from

return $this->belongsTo('App\User');

to

return $this->belongsTo('App\User', 'user_id');

in which user_id is my foreign key in the news table.

like image 44
wobsoriano Avatar answered Nov 06 '22 01:11

wobsoriano


If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.

For example: In a table, you may want to list users with their roles.

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ $user->role->name }}</td>
    </tr>
    @endforeach
</table>

In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
    </tr>
    @endforeach
</table>

Edit: You can use Laravel's the optional method to avoid errors (more information). For example:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user->name }}</td>
        <td>{{ optional($user->role)->name }}</td>
    </tr>
    @endforeach
</table>

If you are using PHP 8, you can use the null safe operator:

<table>
    <tr>
        <th>Name</th>
        <th>Role</th>
    </tr>
    @foreach ($users as $user)
    <tr>
        <td>{{ $user?->name }}</td>
        <td>{{ $user?->role?->name }}</td>
    </tr>
    @endforeach
</table>
like image 28
Mehmet Bütün Avatar answered Nov 05 '22 23:11

Mehmet Bütün


I implemented a hasOne relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.

like image 9
Bruce Tong Avatar answered Nov 06 '22 00:11

Bruce Tong