Title: Write multiple laravel query at once
Tags: laravel
Question: im new to laravel, I just want to know if there's any way to efficiently rewrite this code?

```$answer1 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','1')-&gt;get()-&gt;count();
$answer2 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','2')-&gt;get()-&gt;count();
$answer3 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','3')-&gt;get()-&gt;count();
$answer4 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','4')-&gt;get()-&gt;count();
$answer5 = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16where('answer_1','=','5')-&gt;get()-&gt;count();
```

Comment: 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.


Here is another answer: Get the data first:

```$answers = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16whereIn('answer_1', [1, 2, 3, 4, 5])-&gt;get();
```

Then count answers using loaded collection:

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

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


Here is another answer: 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
```


Here is another answer: Try this:

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

$answer = SurveyAnswer181a:6c1c:918f:f3a4:2e8c:61d6:1a08:6b16whereId('answer_1', $matches)-&gt;groupBy('answer_1')-&gt;get();
```


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:06/10/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<laravel>', 'Title': 'Write multiple laravel query at once', 'ViewCount': 59, 'id': 44473802, 'user_AboutMe': '', 'user_AccountId': 9125754.0, 'user_DisplayName': 'Cath', 'user_Reputation': 43.0, 'user_Views': 3.0, 'user_id': 6789548.0}}