Reputation: 1380
I'm trying to create a simple activity feed where a user can see his friends' updates.
I'm dealing with three tables. user_status, friendship and users.
users table
user_id
name
email
..(a regular users table, nothing special)
friendship table
friendship_id
friend_one (Foreign key from users table)
friend_two (Foreign key from users table)
user_status table
status_id
user_id (foreign key from users table)
status
date
MODELS
User Model
public function friends() {
return $this->belongsToMany('App\Models\User', 'friendship', 'friend_one', 'friend_two');
}
public function status() {
return $this->hasMany('\App\Models\UserStatus','status_id');
}
UserStatus Model
public function usersStatus() {
return $this->belongsTo('\App\Models\User','user_id');
}
FeedController.php
class FeedController extends Controller
{
public function index() {
$friends = Auth::user()->friends;
return view('frontend.feed.index')
->with('friends',$friends);
}
}
Using the query below, I can get a user's friends. I also can get a specific user's status updates easily, but I have no idea how to list only specific users' statuses.
@foreach($friends as $friend)
{{$friend->email}}
@endforeach
The one below doesn't work.
View
@foreach($friends as $friend)
@foreach($friend->status as $status)
{{$status->status}}
@endforeach
@endforeach
Invalid argument supplied for foreach() (View: /Applications/MAMP/htdocs/master/resources/views/frontend/feed/index.blade.php)
Upvotes: 0
Views: 1003
Reputation: 2790
I think the problem is with your foreign_key reference in
public function status() {
return $this->hasMany('\App\Models\UserStatus','status_id');
}
Change to :
public function status() {
return $this->hasMany('\App\Models\UserStatus', 'user_id', 'user_id');
}
and it should work.
Upvotes: 1