Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // CONTROLLER
- class UserController extends Controller
- {
- public function index()
- {
- $users = User::orderBy('created_at')->get()->groupBy(function($item) {
- return $item->created_at->format('Y-m-d');
- });
- return view('users', compact('users'));
- }
- }
- // NOTES
- 1. Function groupBy() is called AFTER the get(), it is a Collection function and not Eloquent.
- If you do groupBy() before get(), it wouldn’t work, cause Eloquent groupBy() doesn’t accept callback parameter.
- 2. I’m doing group by formatted column $item->created_at->format(‘Y-m-d’), it will work only on created_at/updated_at column
- that are automatically transformed to Carbon objects. If you want to group by other date/time fields, you should use Carbon,
- like Carbon::createFromFormat(‘Y-m-d H:i:s’, $item->register_time)
- // VIEW
- <table class="table">
- @foreach ($users as $day => $users_list)
- <tr>
- <th colspan="3"
- style="background-color: #F7F7F7">{{ $day }}: {{ $users_list->count() }} users</th>
- </tr>
- @foreach ($users_list as $user)
- <tr>
- <td>{{ $user->name }}</td>
- <td>{{ $user->email }}</td>
- <td>{{ $user->created_at }}</td>
- </tr>
- @endforeach
- @endforeach
- </table>
- As you can see, we can still call $users_list->count() on the result, too. Pretty convenient.
- So, that’s it. In short, you can do groupBy() with callback function, after getting all query results.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement