So I am learning Laravel 5 and have a question regarding many to many relationships. I'm building a twitter clone, and want to allow for creating tweets and retweeting. My database setup is (as outlined in the laravel docs for a pivot table)
users
- id
- name
tweets
- id
- content
tweet_user
- tweet_id
- user_id
My User
and Tweet
model have the appropriate belongsToMany
calls to hook up those relationships.
from User.php
public function tweets() {
return $this->belongsToMany('App\Tweet');
}
from Tweet.php
public function users() {
return $this->belongsToMany('App\User');
}
Finally, my tweet_user pivot table looks like:
|--------------------|
| tweet_id | user_id |
|--------------------|
| 1 | 1 |
|--------------------|
| 1 | 2 |
|--------------------|
So to display tweets I do:
return view('tweets.index')->withTweets(App\Tweet::all())
And pass that to my view. All good at this point, my view will display 2 tweets (as seen in the tweet_user pivot table above) My view then has:
@foreach($tweets as $tweet)
{{ $tweet->user->name }} <-issue is here
{{ $tweet->content }} <- all good here
@endforeach
So since I have this setup as many to many, the $tweet->user
is an array / collection of all users that have this tweet. How do I access the actual user model for the current tweet in the loop above (IE user id 1 for the first loop, user id 2 for the second)? I'm sure I'm missing something simple, but do I need some other accessor on the tweet / user model? I initially had this setup as a hasMany
/ belongsTo
relationship, so the loop above worked fine. Thanks for any help!
I would rename $this->user
to $this->users
if it were a many to many, just for the ease of reading.
Then something like:
@foreach($tweets as $tweet)
@foreach($tweet->users as $user)
{{ $user->name }}
@endforeach
{{ $tweet->content }} <- all good here
@endforeach
This is because you have a many to many relationship set up. You might want to sort by order or someway to flag the original user though.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments