Hello Geek, Today’s tutorial will teach you How to Calculate Average in Laravel Collection. You’ve come to the right place if you want to see a sample of the Laravel collection. Calculate the column average. Let’s look at how to calculate the column average in the Laravel collection. It’s a straightforward example of a Laravel collection calculating the average column. To get the average of column values in Laravel, follow the steps below.
This example is applicable to Laravel 6, Laravel 7, Laravel 8, and Laravel 9.
Simply follow the steps below to obtain the layout shown below:
Step 1: Install Laravel
this is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command, or learn How to install laravel 9 – Laravel Installation Guide
composer create-project laravel/laravel example-app
Step 2: Create Route
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FindController;
/*
|--------------------------------------------------------------------------
| 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('/average',[FindController::class, 'index']);
Step 3: Create Controller
FindController will be created. as evidenced by the following code and output:
php artisan make:controller FindController
App\Http\Controllers\FindController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FindController extends Controller
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
$data = [
["price" => 27],
["price" => 46,
["price" => 12]
];
dd(collect($data)->average('price'));
}
}
Step 4: Start Development Server
php artisan serve
You can now open the following URL in your browser:
http://localhost:8000/average
Happy coding nerding out.