Laravel Group By First Letter Example Tutorial

By Hardik Savani November 5, 2023 Category : Laravel

Hey Artisan,

I am going to show you an example of laravel group by first letter. This article goes in detailed on group by first letter in laravel. if you want to see an example of laravel group by first letter users then you are in the right place. I would like to share with you group by with first letter in laravel.

In this example, We'll use an example of a users table where we want to group users by the first letter of their name column. we will use SUBSTRING() sql function and groupBy() laravel eloquent method. so, let's follow the steps:


Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Controller

In this step, we will create UserController with index() where we getting records and group by it. so let's create controller using bellow command.

php artisan make:controller UserController

Now, update the code on the controller file.



namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use DB;

class UserController extends Controller



* Display a listing of the resource.


* @return \Illuminate\Http\Response


public function index(Request $request)


$users = User::select('name', DB::raw("SUBSTRING(name, 1, 1) as first_letter"))




return view('users', compact('users'));



Step 3: Add Route

Furthermore, open routes/web.php file and update code on it.



use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;



| Web Routes



| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!



Route::get('users', [UserController::class, 'index']);

Step 4: Create View File

In Last step, let's create users.blade.php for display users and put following code:


<!DOCTYPE html>



<title>Laravel Group By with First Latter Example -</title>

<meta name="csrf-token" content="{{ csrf_token() }}">

<link href="" rel="stylesheet">



<div class="container">

<h1>Laravel Group By with First Latter Example -</h1>

@foreach ($users as $letter => $userGroup)

<h2>{{ $letter }}</h2>


@foreach ($userGroup as $user)

<li>{{ $user->name }}</li>







Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:


Now we are ready to run this example and check it...

I hope it can help you...

Tags :