Abid
Abid

Reputation: 129

Why Eloquent HasMany return an empty collection?

Hi why i get an empty collection when i use $user->posts as property. However i do a get collection when i use $user->posts() as function.

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

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

    public function index(User $user){
        dd($user->posts);
         return view('home', compact('user'));
    }

    @foreach($user->posts as $post)
        <p>$post->title</p>
        <p>$post->body</p>
    @endforeach
result
Collection {#1102 ▼
  #items: []
}

Upvotes: 0

Views: 102

Answers (2)

Muabazalm
Muabazalm

Reputation: 364

User model:

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

Post model:

public function user(){
    return $this->hasMany(Post::class);
}

And make sure you have user_id column on your post table

Upvotes: 0

Rouhollah Mazarei
Rouhollah Mazarei

Reputation: 4153

The first method (user) should be in your post model.

The second method (posts) should be in your user model.

Check your database and see if the posts table has a column named user_id.

Check your database and see if the user_id column has a valid value (according to the users table.

Also make sure your route has {user} in it. Something like this:

Route::get('home/{user}', 'Cotroller@method')

Upvotes: 2

Related Questions