php - Laravel count is not working, any support?
Get the solution ↓↓↓I am trying to output user details on api i am using laravel 6 butcount
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
}
Answer
Solution:
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();
Answer
Solution:
I recommend usingwithCount()
. Check docs
$user = User::find($req->username)->withCount('likes')->get();
$user->likes_count // this will give you user's like count
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: warning: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.