0

I am trying to output user details on api i am using laravel 6 but count is giving me unexpected output may be it is not woking so i don't how any one can help

 public function userDetails(User $user, Request $req){ $user = $user->find($req->username); if(empty($user))//check if user exists return response()->json(["msg"=>"No user found "],404); $user->profile = empty($user->profile) ? "" : $user->profile->file; $user->downloads = empty($user->downloads) ? 0 : $user->downloads->count('id'); $user->likes = empty($user->likes) ? 0 : $user->likes->count(); $user->reads = empty($user->reads) ? 0 : $user->reads->count(); $user->dislikes = empty($user->dislikes) ? 0 : $user->dislikes->count(); return response()->json($user, 200); } 

output

{ "username": "liberi", "firstName": null, "secondName": null, "gender": null, "phone": "0987654321", "email": "[email protected]", "created_at": "2020-05-12 21:48:33", "updated_at": "2020-05-12 21:48:33", "email_verified_at": null, "phone_verified_at": null, "profile": null, "downloads": [], "likes": [ { "id": 1, "book_ISBN": "09876543236", "user_username": "liberi", "created_at": null, "updated_at": null }, { "id": 2, "book_ISBN": "09876543236", "user_username": "liberi", "created_at": null, "updated_at": null } ], "reads": [], "dislikes": [] } 

expected out put

{ "username": "liberi", "firstName": null, "secondName": null, "gender": null, "phone": "0987654321", "email": "[email protected]", "created_at": "2020-05-12 21:48:33", "updated_at": "2020-05-12 21:48:33", "email_verified_at": null, "phone_verified_at": null, "profile": null, "downloads": 0, "likes": 2, "reads": 0, "dislikes": 0 } 
4
  • 1
    You may need to do like so: $user->likes()->count(). Note the parentheses. Commented May 22, 2020 at 14:54
  • it is giving me the same Commented May 22, 2020 at 14:57
  • Can't be giving you the same, this is the same as the accepted answer :) Commented May 22, 2020 at 15:24
  • i checked well and it worked Commented May 23, 2020 at 19:51

2 Answers 2

1

You might find it easier to use the query builder to get the count instead of the relationship/collection, by adding the parenthesis on the relationship. You can even skip the ternary.

$user->downloads = $user->downloads()->count('id'); $user->likes = $user->likes()->count(); $user->reads = $user->reads()->count(); $user->dislikes = $user->dislikes()->count(); 
Sign up to request clarification or add additional context in comments.

1 Comment

it worked i checked well your answer and found it helping me
0

I recommend using withCount(). Check docs

$user = User::find($req->username)->withCount('likes')->get(); $user->likes_count // this will give you user's like count 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.