1

im new to laravel, I just want to know if there's any way to efficiently rewrite this code?

$answer1 = SurveyAnswer::where('answer_1','=','1')->get()->count();
$answer2 = SurveyAnswer::where('answer_1','=','2')->get()->count();
$answer3 = SurveyAnswer::where('answer_1','=','3')->get()->count();
$answer4 = SurveyAnswer::where('answer_1','=','4')->get()->count();
$answer5 = SurveyAnswer::where('answer_1','=','5')->get()->count();
1
  • Hi, thanks for the answers, both worked. Im sorry if my question was incomplete. But what im trying to do is to count specific data in my table and display it in a page. I have 20 queries from different questions. Each questions have 5 answers. I want to count how many of each answers were recorded. I just want to know if there's better way to do it so that I won't have to write the same lines of codes 20 times. Thank you so much for your time. Commented Jun 10, 2017 at 14:12

3 Answers 3

1

Get the data first:

$answers = SurveyAnswer::whereIn('answer_1', [1, 2, 3, 4, 5])->get();

Then count answers using loaded collection:

$answer1 = $answers->where('answer_1', 1)->count();
$answer2 = $answers->where('answer_1', 2)->count();
...

This code will generate just one DB query instead of five.

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

Comments

0

Try this:

$matches = [1,2,3,4,5];

$answer = SurveyAnswer::whereId('answer_1', $matches)->groupBy('answer_1')->get();

Comments

0

You can easily do it with an agregate function with a case expression, since mysql doesnot support native pivoting functions Following is a sample, and try to rewrite according to your requirement and runt it against database directly, if it works, then you can use it with laravel raw sql.

 select id,
 sum(case when value = 1 then 1 else 0 end) ANSWER1_COUNT,
 sum(case when value = 2 then 1 else 0 end) ANSWER2_COUNT
from survey
group by answer

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.