Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to select certain fields in Laravel Eloquent?
Laravel Eloquent provides several methods to select specific fields from database tables instead of retrieving all columns. This approach improves performance by reducing memory usage and network traffic.
Using select() Method
The select() method allows you to specify which fields to retrieve
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index() {
$users = User::select('name', 'email')->where('id', 1)->get();
foreach ($users as $u) {
echo $u->name."=>".$u->email;
}
}
}
?>
The output of the above code is
Siya Khan=>siya@gmail.com
This is equivalent to the SQL query
SELECT name, email FROM users WHERE id=1;
Using get() with Field Array
Another approach is passing field names directly to the get() method
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index() {
$users = User::where('id', 1)->get(['name','email']);
foreach ($users as $u) {
echo $u->name."=>".$u->email;
}
}
}
?>
The output of the above code is
Siya Khan=>siya@gmail.com
Using all() Method
The all() method retrieves all records with specified fields only
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index() {
$users = User::all(['name','email']);
foreach ($users as $u) {
echo $u->name."=>".$u->email." ";
}
}
}
?>
The output of the above code is
Siya Khan=>siya@gmail.com Heena Khan=>heena@gmail.com Seema=>SZJj8osSc1@gmail.com Neha Singh=>KBc9tUG3pp@gmail.com
Using pluck() Method
The pluck() method creates a key-value pair collection
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index() {
$users = User::where('id', 1)->pluck('name', 'email');
print_r($users->toArray());
}
}
?>
The output of the above code is
Array ( [siya@gmail.com] => Siya Khan )
Using find() Method
The find() method retrieves a single record by primary key with specified fields
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller {
public function index() {
$user = User::find(1, ['name', 'email']);
echo "Name: " . $user->name . ", Email: " . $user->email;
}
}
?>
The output of the above code is
Name: Siya Khan, Email: siya@gmail.com
Conclusion
Laravel Eloquent offers multiple methods to select specific fields: select() for query building, get() with arrays for simple retrieval, and pluck() for key-value collections. Choose the method that best fits your data structure needs.
