In this article, I’ll show you how to get the minimum value of a column in Laravel 11 using the built-in min(), oldest(), and orderBy() methods. This method is a quick and efficient way to find the smallest value in a database column, whether you're working with numbers, dates, or other comparable data types.
Steps to Get Minimum Value of a Column in Laravel 11:
Use the min()
Method in Query Builder:
Laravel's query builder provides a min()
method to get the smallest value in a column.
Example:
If you have a table named products
with a column price
, you can find the minimum price like this.
$minPrice = DB::table('products')->min('price');
echo "The minimum price is: " . $minPrice;
Use the min()
Method with Eloquent:
If you're using Eloquent models, you can also use the min()
method.
Example:
$minPrice = Product::min('price');
echo "The minimum price is: " . $minPrice;
Using orderBy()
Method:
The orderBy()
method sorts the records by a specified column, and you can retrieve the smallest value by picking the first record.
Example:
Retrieve the product with the lowest price.
$minPriceProduct = Product::orderBy('price', 'asc')->first();
if ($minPriceProduct) {
echo "The minimum price is: " . $minPriceProduct->price;
} else {
echo "No products found.";
}
oldest()
Method:The oldest()
method sorts the records by a specified column in ascending order. It defaults to the created_at
column if no column is specified. You can specify a different column to find the smallest value.
Example:
Retrieve the oldest product based on the price
column.
$minPriceProduct = Product::oldest('price')->first();
if ($minPriceProduct) {
echo "The minimum price is: " . $minPriceProduct->price;
} else {
echo "No products found.";
}
You might also like:
In this article, we will see laravel 9 form collective example. Here, we will learn how to use collective form and...
Jan-20-2023
In this article, I’ll guide you through creating relationships with JSON columns in a Laravel application. Sometim...
Dec-05-2024
In our ever-changing digital landscape, staying ahead of the competition is essential. And that's precisely what we&...
Jan-11-2023
Hello, laravel web developers! In this article, we'll see how to Socialite login with Slack in laravel 11. In l...
Aug-16-2024