1

In my app i have a Posts and a Reacts table both are connected with relationship.

In App user can react to a post(like or dislike) and for retrieve this i'm using this function :

public function feed()
{
    $posts=Post::with('user')
                ->with('reacts')
                ->withCount('comments')
                ->orderBy('created_at', 'DESC')
                ->get();
    return response()->json(["posts" => $posts]);
}

the response is:

enter image description here

i want to add one more field in Posts Object for isUserLiked and if the current authenticated user liked the post then value will be true or false for him something like this:

enter image description here

i can add a additional field but how can i set the value dynamically for that

this is what i am doing in my Post Model:

 protected $appends = ['isUserLiked'];
 public function getIsUserLikedAttribute($id)
 {
    $react=React::where('user_id',auth()->user()->id)->where('post_id',$id)->exists();
    return $react;
 }

this is returning false because i don't know any way to pass the arguments(Post id). is there any better way i can get the desired response? Thanks!

3
  • 2
    Since that is the post model you can just do $this->id Commented Jul 19, 2019 at 20:00
  • 1
    If you have a relationship between Post and React, you could simplify that to $this->react->where("user_id", "=", auth()->user()->id)->exists(); Commented Jul 19, 2019 at 20:02
  • lot of thanks to you! Commented Jul 19, 2019 at 20:04

2 Answers 2

1
public function getIsUserLikedAttribute($id)
 {
    return React::where('user_id',auth()->user()->id)->where('post_id',$this->id)->exists();

 }
Sign up to request clarification or add additional context in comments.

Comments

1

In your user model:

public function reacts(){
   return $this->hasMany(React::class);
}

public function scopeReactOnPost($query, $post_id){
   return $this->reacts()->where(function($query) use ($post_id){
      $query->where('post_id',$post_id);
   });
}

and in your controller:

$user->reactOnPost($post_id)->first();

or

$user->reactOnPost($post_id)->get()->count();

Will let you know if user had any reaction on the specified post. and for adding this to your json output you can artisan make a resource for your post model. Laravel Resources

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.