When working with Laravel, many developers simply fetch data using all() or get() without thinking much about it.
So instead of doing that, Laravel gives us a simple method called select(). In this blog, we’ll understand how to use select() with a simple example.

Prerequirement:
- Composer (latest version)
- Laravel version 12
Steps to Optimize Queries using select() in Laravel Eloquent:
- Create a new Laravel project
- Create migration and model
- Add dummy data
- Create controller
- Use the select() method
- Test the output
Step 1: Create a New Laravel Project
composer create-project laravel/laravel select-demoMove into the project:
cd select-demo
php artisan serveStep 2: Create Model and Migration
php artisan make:model Product -mNow open the migration file and update it:
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description');
$table->decimal('price', 10, 2);
$table->integer('stock');
$table->timestamps();
});
}Run migration:
php artisan migrateStep 3 : Add Dummy Data
Instead of adding data manually, we can use a Seeder
Run this command:
php artisan make:seeder ProductSeederNow open,
database/seeders/ProductSeeder.php
and edit as below,
public function run(): void
{
Product::create([
'name' => 'Laptop',
'description' => 'Gaming Laptop',
'price' => 75000,
'stock' => 5
]);
Product::create([
'name' => 'Mobile',
'description' => 'Smartphone',
'price' => 20000,
'stock' => 10
]);
}Step 4 : Create Controller
php artisan make:controller ProductControllerStep 5 : Use the select() Method
use App\Models\Product;
public function index()
{
$products = Product::select('id', 'name', 'price')->get();
return response()->json($products);
}Step 6 : Add Route
use App\Http\Controllers\ProductController;
Route::get('/products', [ProductController::class, 'index']);Step 7 : Test the Output
Now open your browser and hit the URL below,
http://127.0.0.1:8000/products
And after hitting the url, you will get the output as below,
[
{
"id": 1,
"name": "Laptop",
"price": "75000.00"
}
]Conclusion:
The select() method is simple, but very useful when you want to optimize your queries.
Instead of fetching everything, just get what you need.

FAQ
1. What is Laravel Eloquent?
Laravel Eloquent is an Object-Relational Mapping (ORM) system that allows developers to interact with the database using PHP models instead of writing raw SQL queries.
2. Why is query optimization important in Laravel?
Query optimization improves application performance by reducing database load, speeding up data retrieval, and minimizing server resource usage.



