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 a laravel 9 firebase push notification, a firebase notification through you can notify...
Sep-20-2022
In this article, we will see how to install vue js in the laravel framework. if you are not aware of you are freshe...
Jul-12-2020
In this article, I'll show you how to read CSV files in Python. Using Python, we can easily read CSV files line by l...
Sep-18-2024
In this article, we will explore the process of converting a PHP array into a JSON object. We'll achieve this transf...
Jul-08-2020