How to Get Min Value of Column in Laravel 11

Websolutionstuff | Jan-07-2025 | Categories : Laravel MySQL

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.";
}

 

Using 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:

Recommended Post
Featured Post
Laravel 9 Firebase Push Notification
Laravel 9 Firebase Push Notifi...

In this article, we will see a laravel 9 firebase push notification, a firebase notification through you can notify...

Read More

Sep-20-2022

How To Install VueJs In Laravel
How To Install VueJs In Larave...

In this article, we will see how to install vue js in the laravel framework. if you are not aware of you are freshe...

Read More

Jul-12-2020

How to Read CSV File in Python Example
How to Read CSV File in Python...

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...

Read More

Sep-18-2024

How To Convert PHP Array To JSON Object
How To Convert PHP Array To JS...

In this article, we will explore the process of converting a PHP array into a JSON object. We'll achieve this transf...

Read More

Jul-08-2020