Do you know that Laravel 8.x provide some powerfull eloquent aggregate function to fecth max, avg, sum etc. Eloquent provides withMin
, withMax
, withAvg
, and withSum
methods. These methods will place a {relation}_{function}_{column}
attribute on your resulting models:
This tutorial is focused on laravel eloquent aggregate function. If you want to see example of laravel eloquent withMax() then you are the right place. I am going to explain simply step by step laravel eloquent withMin(). We will take a look at example of laravel with max eloquent. So, let's follow few step to create example of laravel withmin.
See the below example to understand
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* Get the comments for the blog post.
*/
public function products()
{
return $this->hasMany(Product::class);
}
}
Product Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'price'
];
}
withMin() Example:
namespace App\Http\Controllers;
use App\Models\Category;
class TestController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$categories = Category::select("id", "name")
->withMin('products', 'price')
->get()
->toArray();
dd($categories);
}
}
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Mobile
[products_min_price] => 100
)
[1] => Array
(
[id] => 2
[name] => Laptop
[products_min_price] => 200
)
)
withMax() Example:
namespace App\Http\Controllers;
use App\Models\Category;
class TestController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$categories = Category::select("id", "name")
->withMax('products', 'price')
->get()
->toArray();
dd($categories);
}
}
Output
Array
(
[0] => Array
(
[id] => 1
[name] => Mobile
[products_max_price] => 120
)
[1] => Array
(
[id] => 2
[name] => Laptop
[products_max_price] => 210
)
)
Hope it can help you.
#laravel #laravel-8x #eloquent-tips