vendredi 29 décembre 2017

Trying to get property of non-object when using One to Many relationship in Laravel

So I keep getting this error when trying to get the name of the user who created a post.

My models look like this:

class User extends Authenticatable {
    use Notifiable, CanResetPassword;

    public function posts() {
        return $this->hasMany('App\Post');
    }
}

&

class Post extends Model {

    public function user() {
        return $this->belongsTo('App\User', 'user_id');
    }
}

I try to display the name by doing this in my view:

@foreach($posts as $post)
    <tr>
        <td></td>          
    </tr>
@endforeach

And my controller looks like this:

public function getAdminIndex() {
    $posts = Post::orderBy('id', 'desc')->get();
    $comments = Comment::all();
    $likes = Like::all();
    $users = User::all();

    return view('admin.index', ['posts' => $posts, 'comments' => $comments, 'likes' => $likes, 'users' => $users]);
}

Can anyone please tell me what I'm doing wrong?

Thank you very much!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2CoG4Qg
via IFTTT

Aucun commentaire:

Enregistrer un commentaire