2

I have 3 Models "Category", "Post", and "User". A Category has a hasMany relationship with Post. And a Post has a belongsTo relationship with User.

I have a Category object $cat1 and i can access its posts (and the user_id) in my view, but i can't access more user data (line name)

@foreach ($cat1->posts as $post)
    {{ $post->title }}
    {{ $post->user()->name }}
@endforeach

This throws an error

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name

Eddie
  • 26,593
  • 6
  • 36
  • 58
Badr
  • 177
  • 4
  • 17

1 Answers1

5

You can access it like this:

{{ $post->user->name }}

When you call the function, it's to query the relationship.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58