0
votes

I'm using Laravel and I get this error:

Trying to get property of non-object (View: C:\laragon\www\al-Zad\resources\views\blog\index.blade.php)

The problem is in this line:

 <li><i class="fa fa-user"></i><a href="#"> {{$post->author->name}} </a></li>

These are the models:

post model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class post extends Model
{

    public function author()
    {
        return $this->belongsTo(User::class);
    }
}

User model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts()
    {
     return $this->hasMany(post::class);   
    }
}

How can I fix the problem?

1
Does that post have an author? - aynber
The post doesn't have an author. Or your relationship isn't working. - DevK

1 Answers

-1
votes

in your post model you should add this function:

public function author(){
  return $this->hasOne('App\User');
}

and in the view you should put this:

{{$post->author()->name}}