php - Load all posts and check if the post is liked or not in laravel -


i have post model , like model.

when go user page, can see posts liked. now, want indicate small icon if post liked logged in user visiting user page.

this how select liked posts of user (not logged user profile owner):

$likespost = post::with('user')->join('likes', function ($join) use ($user) {     $join->on('likes.likeable_id', '=', 'id')->where('likes.user_id', '=', $user->id)->where('likes.likeable_type','=', post::class); })->get(); 

now want check if authenticated user has liked post or not along query. i've tried many things i'm not sure how should approach problem. i'm using polymorphic relations.

first, change initial query little bit. i'd posts liked user (assuming post has likes relationship):

$profilelikedposts = post::wherehas('likes', function($query) use ($user) {         return $query->where('user_id', $user->id);     })     ->get(); 

next, can liked posts of logged in user this:

// "wherein" limits results posts retrieved // profile user. not required, gives little performance boost // if collection doesn't need non-profile-liked posts.  $authuser = auth::user(); $authlikedposts = post::wherehas('likes', function($query) use ($authuser) {         return $query->where('user_id', $authuser->id);     })     ->wherein('id', $profilelikedposts->lists('id'))     ->get(); 

now, in blade template, loop through liked posts profile user ($profilelikedposts), can use collection contains() method check if post liked logged in user:

@foreach ($profilelikedposts $post)     // ...     @if ($authlikedposts->contains('id', $post->id))         // post liked both; show icon     @endif     // ... @endforeach 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -