Laravel Pluck Multiple Columns Query Example

Hello Artisan

In this laravel pluck example tutorial i will show you how we can fetch single or multiple data using laravel pluck method. Sometimes we need to fetch data from database only single column or two column.

In this tutorial i will show you that we can fetch single or multiple column data using laravel pluck method rather to fetch all data. Hope it can help you to make your query faster.

Suppose we want to fetch only username and email from database. See the below example that how we can write this query.


Route::get('/', function () {

	$collection = app(\App\User::class)
    ->where('id', 1)
    ->get(['name', 'email']);
    
    return $collection;
});

 

Or simply you can use pluck method like below

Route::get('/', function () {

    $collection = \App\User::where('id', 1)->get()->pluck('name', 'email');
    
    return $collection;
});

 

And for printing multiple pluck data, see the below code example

Route::get('/', function () {

    $collection = \App\User::where('id', 1)->get()->pluck('name', 'email');
    
    foreach ($collection as $email => $name) {
    	echo "My name is {$name} and email is {$email}";
    }
});

 

Read also : Laravel Join Query (Left Join, Inner Join, Right Join, Cross Join) Example

 

Hope this Laravel pluck multiple columns example can help you.

 

#laravel #laravel-eloquent