Yashgupta
Yashgupta

Reputation: 211

How can add additional Attribute in my JSON response with dynamic value in laravel

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!

Upvotes: 1

Views: 864

Answers (2)

Amin Bakhtiari Far
Amin Bakhtiari Far

Reputation: 156

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

Upvotes: 1

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

 }

Upvotes: 1

Related Questions