Laravel’s Eloquent can be used to easily retrieve, store, update or delete data. Interestingly, it can also handle tasks such as aggregating and calculating sums, maximum values, or averages. In this post we’ll focus on determining the maximum value in a column.
To determine the maximum value of a column with Eloquent you can use 2 methods:
// Method 1: Determine maximum value of a column using max()
$highestScore = Score::max('score');
// Method 2: Determine maximum valueof a column using orderByDesc
$highestScore = Score::orderByDesc('score')->first();
Method 1 will only return the highest value (e.g., ‘200’) in a single property . Method 2 will retrieve the complete record associated with the highest score value..
In this tutorial we’ll create a scores
table with player names and their scores. We’ll calculate the max score in our controller and show the winner using a blade view. Since we want to show some information about the winner we’ll be using Method 2.
Let’s get started!
Step 1: Create a Laravel Project
Let’s begin by setting up a new Laravel project. Open your terminal and run the following commands:
composer create-project laravel/laravel max-score-app
cd max-score-app
Step 2: Generate Migrations
To generate a migration for the ‘scores’ table run the following Artisan command:
php artisan make:migration create_scores_table --create=scores
Step 3: Migration Code
Open the generated migration and define the schema for the ‘scores’ table by adding:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateScoresTable extends Migration
{
public function up(): void
{
Schema::create('scores', function (Blueprint $table) {
$table->id();
$table->string('player_name');
$table->integer('score');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('scores');
}
}
Step 4: Run the Migrations
Now execute the following Artisan command to create the ‘scores’ table:
php artisan migrate
Step 5: Create Model
Now let’s generate a model for the ‘Score’:
php artisan make:model Score
Step 6: Model Code
Define the model with fillable columns and timestamp:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Score extends Model
{
protected $fillable = [
'player_name',
'score',
];
}
Step 7: Insert Test Data
Use Laravel Tinker to insert some sample data:
php artisan tinker
After the tinker shell has opened, copy & paste the code below to execute it. This uses a simple call to Eloquent’s create()
method 4 times to insert some sample data, which we can test with:
use App\Models\Score;
Score::create(['player_name' => 'Bruce Banner', 'score' => 150]);
Score::create(['player_name' => 'Peter Parker', 'score' => 200]);
Score::create(['player_name' => 'Peter Jason Quill', 'score' => 180]);
Score::create(['player_name' => 'Natasha Romanoff', 'score' => 190]);
After running this, the database should now contain the following records:
Step 8: Create a Controller
Now we’ll create a controller by running the following command:
php artisan make:controller ScoreController
Step 9: Add Controller Code
Now edit the generated ScoreController.php
and add the following code to calculate the maximum score and return it in a view:
<?php
namespace App\Http\Controllers;
use App\Models\Score;
class ScoreController extends Controller
{
public function index()
{
$highScore = Score::orderByDesc('score')->first();
$rankings = Score::orderByDesc('score')->get();
return view('scores.index', compact('rankings', 'highScore'));
}
}
Step 10: Create a View
Now create a new file resources/views/scores/index.blade.php
and add the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Include Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-3">
<h1 class="mt-3 mb-4">Game results</h1>
<div class="card mt-3">
<div class="card-body">
<h2 class="card-title">Winner: <span class="badge bg-success">{{ $highScore->player_name }}</span></h2>
<p class="card-text">High Score: <strong>{{ $highScore->score }}</strong></p>
<p class="card-text">Achieved on: <span class="badge bg-info">{{ $highScore->created_at->format('Y-m-d H:i:s') }}</span></p>
</div>
</div>
<h2 class="mt-3 mb-4">Participants</h2>
<div class="card">
<div class="card-body">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Rank</th>
<th>Player</th>
<th>Score</th>
<th>Achieved on</th>
</tr>
</thead>
<tbody>
@foreach($rankings as $ranking)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{{ $ranking['player_name'] }}</td>
<td>{{ $ranking['score'] }}</td>
<td>{{ $ranking['created_at'] }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
<footer class="mt-5 text-center">
<p>Created with ♥ by Laracoding</p>
</footer>
</body>
</html>
Step 11: Add Route
Define a route to the controller action in routes/web.php
:
<?php
use App\Http\Controllers\ScoreController;
use Illuminate\Support\Facades\Route;
Route::get('/highscores', [ScoreController::class, 'index']);
Step 12: Test the Application
Run the application:
php artisan serve
Visit http://127.0.0.1:8000/highscores
in your browser to see the high score details. It should look like this:
Conclusion
Congratulations! You’ve successfully built an application that calculates and displays the maximum value of a column using Eloquent and present it using a blade view.
Feel free to apply these techniques to your own Laravel projects. Happy coding!
References
- Eloquent (Laravel Documentation)
- Database Migrations (Laravel Documentation)
- Bootstrap 5 Documentation
This entry is part 4 of 4 in the series Aggregating With Laravel Eloquent
- How to Calculate the Average of a Column Using Eloquent
- How to Calculate the Sum of Multiple Columns Using Eloquent
- How to Calculate the Sum of a Relation Column in Eloquent
- How to Get the Max Value of a Column Using Eloquent