Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. // CONTROLLER
  2. class UserController extends Controller
  3. {
  4.  
  5. public function index()
  6. {
  7. $users = User::orderBy('created_at')->get()->groupBy(function($item) {
  8. return $item->created_at->format('Y-m-d');
  9. });
  10.  
  11. return view('users', compact('users'));
  12. }
  13.  
  14. }
  15.  
  16. // NOTES
  17. 1. Function groupBy() is called AFTER the get(), it is a Collection function and not Eloquent.
  18. If you do groupBy() before get(), it wouldn’t work, cause Eloquent groupBy() doesn’t accept callback parameter.
  19. 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
  20. that are automatically transformed to Carbon objects. If you want to group by other date/time fields, you should use Carbon,
  21. like Carbon::createFromFormat(‘Y-m-d H:i:s’, $item->register_time)
  22.  
  23. // VIEW
  24. <table class="table">
  25. @foreach ($users as $day => $users_list)
  26. <tr>
  27. <th colspan="3"
  28. style="background-color: #F7F7F7">{{ $day }}: {{ $users_list->count() }} users</th>
  29. </tr>
  30. @foreach ($users_list as $user)
  31. <tr>
  32. <td>{{ $user->name }}</td>
  33. <td>{{ $user->email }}</td>
  34. <td>{{ $user->created_at }}</td>
  35. </tr>
  36. @endforeach
  37. @endforeach
  38. </table>
  39.  
  40. As you can see, we can still call $users_list->count() on the result, too. Pretty convenient.
  41.  
  42. 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