Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a "select count(*) group by" using laravel eloquent

I would like to execute the follow sentence using laravel eloquent

SELECT *, count(*) FROM reserves  group by day

The only solution occurs to me is to create a view in the DB, but I am pretty sure there is a way to do it in laravel way.

like image 346
Ugo Guazelli Avatar asked Jan 16 '16 14:01

Ugo Guazelli


People also ask

How does groupBy count in Laravel?

You could use this: $reserves = DB::table('reserves')->selectRaw('*, count(*)')->groupBy('day');

What is Take () in Laravel?

you can easily use it with laravel 6 and laravel 7 application. take() will help to get data from a database table with a limit. skip() will help to skip some records when you fetch data from the database table. So, let's see bellow examples that will help you how to use take() and skip() eloquent query in laravel.

How do I write a query in Laravel eloquent?

If you want to use Eloquent, and query any entity to return only results where a relationship exists and meets criteria you can use the whereHas() method with a subquery. User::where('verified', 1) ->whereHas('role', function($query) { $query->whereIn('title', ['seller', 'admin']); })->get();

What is toArray in Laravel?

toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.


2 Answers

You could use this:

$reserves = DB::table('reserves')->selectRaw('*, count(*)')->groupBy('day');
like image 75
Marcin Nabiałek Avatar answered Sep 18 '22 04:09

Marcin Nabiałek


As you wish to do it with Laravel Eloquent I assume you have a model name Reserve. In this case you can use this

$reserve = Reserve::all()->groupBy('day')->count();
like image 28
smartrahat Avatar answered Sep 18 '22 04:09

smartrahat