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 Form Collective Example
Laravel 9 Form Collective Exam...

In this article, we will see laravel 9 form collective example. Here, we will learn how to use collective form and...

Read More

Jan-20-2023

Laravel Relationship with JSON Column
Laravel Relationship with JSON...

In this article, I’ll guide you through creating relationships with JSON columns in a Laravel application. Sometim...

Read More

Dec-05-2024

Laravel 10: New Features And Release Date
Laravel 10: New Features And R...

In our ever-changing digital landscape, staying ahead of the competition is essential. And that's precisely what we&...

Read More

Jan-11-2023

Laravel 11 Socialite Login with Slack Account
Laravel 11 Socialite Login wit...

Hello, laravel web developers! In this article, we'll see how to Socialite login with Slack in laravel 11. In l...

Read More

Aug-16-2024