How to count records in groups in Laravel Eloquent?

I have a database that contains information about books and their authors. I want to know how many books each author has written.

J.K. Rowling - "Harry Potter and the Philosopher's Stone"
J.K. Rowling - "Harry Potter and the Chamber of Secrets"
Stephen King - "The Shining"
Stephen King - "It"
Agatha Christie - "Murder on the Orient Express"

I want to end up with a result like this:

Total Books: 5
J.K. Rowling - 2 books
Stephen King - 2 books
Agatha Christie - 1 book

How can I count the number of books written by each author in my database?

You can use the groupBy and count in the query builder to get your desired result.

$books = Book::groupBy('author')
->select('author', DB::raw('count(*) as total'))->->get();

foreach ($books as $book) {
    echo "Author " . $book->author . " - " . $book->total . " books";