1

I want to count the number of date appear in my table using Laravel 5 and SQL Query:

$tanggal = DB::table('entry')->count('*')->groupBy(DATE_FORMAT(created_at,'%d-%m-%Y'));

But it can't work. Help me.

2
  • it can't work...can you be more specific? Are there errors in your logs? Do you see an error in your browser? Commented Nov 20, 2015 at 2:43
  • the error is "Call to a member function groupBy() on integer" Commented Nov 20, 2015 at 2:44

1 Answer 1

2

When you call count(), it is returning the number (as you saw in your error). Try swapping the functions and setting the groupBy parameter to be calculated raw:

$tanggal = DB::table('entry')
             ->groupBy(DB::raw("DATE(created_at)")
             ->count('*');

When you call table() it starts a query builder instance. A lot of query builder methods return the query builder again for method chaining, but some of them are final and return a result like get(), first(), and in this case count().

I haven't tested the above code, but it should be close. You will also notice I changed it from DATE_FORMAT to just DATE. I can see you are trying to exclude the timestamp portion, and you can just use the latter instead of reformatting (which may slow down the query a tiny bit).


EDIT:

Ok, your question was not explained very well. From your comment, I think this is what you are looking for. Also, don't forget, Eloquent is a fantastic ORM, but it isn't a silver bullet and sometimes you may have to just raw plain SQL queries.

$results = DB::table('entry')
             ->addSelect(DB::raw('COUNT("*") as total)')
             ->groupBy(DB::raw("DATE(created_at)")
             ->get();
Sign up to request clarification or add additional context in comments.

3 Comments

but i only get one result using this query, how to get all result?
If you want all of the results, count() is not what you want to do. That method counts the number of records that match and then returns the total count. If you want the records instead of the count, replace ->count('*') with ->get()
but i want to get all of the date and the number of its appearance

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.