Abdallah Sakre Abdallah Sakre - 5 months ago 8
PHP Question

Not able to pass a variable in laravel

In the controller below, if I return

$friendPosts
(which has the post ids), the ids are shown in the view without problems.

But when I try to return the
$sharedPosts
(which has the whole row), nothing shows up in the view.

Controller



public function getProfile($email)
{
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::where('id', $friendPosts)->get();

return view('profile.index')
->with ('friendShares', $sharedPosts);
}


View



@foreach ($friendShares as $friendShares)
<p> {{$friendShares}}</p>
@endforeach

Answer
$myFriends    = Auth::user()->friends()->lists('id');                 
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts  = $friendShares->lists('post_id');
$sharedPosts  = Post::where('id', $friendPosts)->get();

should be

$myFriends    = Auth::user()->friends()->lists('id');                 
$friendShares = Share::whereIn('user_id',$myFriends)->get();
$friendPosts  = $friendShares->lists('post_id');
$sharedPosts  = Post::whereIn('id', $friendPosts)->get();

You are working with more ids, not just one, so you have to use whereIn() which looks trough an array of values.

Next time it would be useful if you tell us what you actually wanted/tried to do with your code.