265

lets say I have 7 columns in table, and I want to select only two of them, something like this

SELECT `name`,`surname` FROM `table` WHERE `id` = '1';

In laravel eloquent model it may looks like this

Table::where('id', 1)->get();

but I guess this expression will select ALL columns where id equals 1, and I want only two columns(name, surname). how to select only two columns?

Amir
  • 8,821
  • 7
  • 44
  • 48
devnull Ψ
  • 3,779
  • 7
  • 26
  • 43
  • 2
    Thanks for asking the question. It's crazy as I've always done this properly in 'classic' SQL queries, but having to use Eloquent, I found it so confusing I was happy just to get it working, and was oblivious to how much memory my queries were using because I was selecting everything. – Jonny Perl Sep 30 '19 at 21:50
  • 1
    ModelName::findOrFail(1, ['name', 'surname']); – Raskul Mar 09 '21 at 00:58

24 Answers24

391

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • 2
    let's suppose i want to select every field expect one how can i do that – Prince Arora Mar 05 '18 at 11:15
  • 5
    First of all, when you have question, ask one. And for your case - just mention all columns instead of the one you don't want to include. It's that easy. – Marcin Nabiałek Mar 05 '18 at 15:16
  • 2
    isn't there any other method for doing that without mentioning all columns – Prince Arora Mar 10 '18 at 04:24
  • 2
    This works for a basic case with a single table. However, if you are using a relation over a pivot table, then this will ALSO select the pivot columns, automatically. – Benubird Apr 03 '18 at 15:15
  • Does it format SQL with this fields, or it filters output data? – POV Nov 19 '18 at 20:02
  • 2
    @OPV It just runs `SELECT name, surname FROM Table where id = 1` SQL query – Marcin Nabiałek Nov 19 '18 at 22:49
  • I see you applied the get method at the end which runs the query on the query builder instance, I'm wondering does this return a collection of say the User objects (the active record way) or just an array containing the results from the underlying SQL query? – fokosun Aug 12 '20 at 19:34
  • How to get field twice with alias? –  Jan 10 '21 at 15:53
  • came here just to check if I was thinking right about not needing to `select(['field1','field2'])` this way without the array is cleaner and better hehe. Thanks for your answer – Daniel Saito Jul 07 '22 at 12:25
  • @MarcinNabiałek, may I ask you to have a look at a Laravel search related question here: https://stackoverflow.com/questions/76485513/laravel-search-with-multiple-keywords-against-multiple-columns-with-the-search ? – Istiaque Ahmed Jun 15 '23 at 21:36
134
Table::where('id', 1)->get(['name','surname']);
Djave
  • 8,595
  • 8
  • 70
  • 124
Utkarsh Pandey
  • 1,682
  • 1
  • 12
  • 11
  • 2
    I want the same thing but using different method. I want to select method by creating instance of model and then select column. i.e $model = new MyModel(); $model->select(['col1', 'col2']); But this thing is not working – Dhirender Mar 20 '18 at 13:01
  • I believe this is the way it is supposed to be used. I don't know if select() is faster than get() though. – m33ts4k0z Apr 06 '21 at 18:25
  • can also be `model::where('col', val)->get(['col1', 'col2']);` – Liam O'Toole Nov 22 '21 at 20:41
98

You can also use find() like this:

ModelName::find($id, ['name', 'surname']);

The $id variable can be an array in case you need to retrieve multiple instances of the model.

Sammie
  • 1,551
  • 1
  • 21
  • 17
91

By using all() method we can select particular columns from table like as shown below.

ModelName::all('column1', 'column2', 'column3');

Note: Laravel 5.4

Sivakumar Tadisetti
  • 1,007
  • 7
  • 12
  • 1
    I want the same thing but using different method. I want to select method by creating instance of model and then select column. i.e $model = new MyModel(); $model->select(['col1', 'col2']); But this thing is not working. – Dhirender Mar 20 '18 at 13:01
47

You first need to create a Model, that represent that Table and then use the below Eloquent way to fetch the data of only 2 fields.

Model::where('id', 1)
         ->pluck('name', 'surname')
         ->all();
Mahesh Yadav
  • 2,416
  • 20
  • 23
32

Also Model::all(['id'])->toArray() it will only fetch id as array.

Bhagchandani
  • 548
  • 6
  • 21
24

Get the value of one column:

Table_Name::find($id)->column_name;

you can use this method with a where clause:

Table_Name::where('id',$id)->first()->column_name;

or use this method to bypass PhpStorm "Method where not found in App\Models":

Table_Name::query()->where('id','=',$id)->first()->column_name;

in query builder:

DB::table('table_names')->find($id)->column_name;

with where clause:

DB::table('table_names')->where('id',$id)->first()->column_name;

or

DB::table('table_names')->where('id',$id)->first('column_name');

last method result is an array

Mostafa Asadi
  • 339
  • 4
  • 8
17

You can use get() as well as all()

ModelName::where('a', 1)->get(['column1','column2']);
aleXela
  • 1,270
  • 2
  • 21
  • 34
12

From laravel 5.3 only using get() method you can get specific columns of your table:

YouModelName::get(['id', 'name']);

Or from laravel 5.4 you can also use all() method for getting the fields of your choice:

YourModelName::all('id', 'name');

with both of above method get() or all() you can also use where() but syntax is different for both:

Model::all()

YourModelName::all('id', 'name')->where('id',1);

Model::get()

YourModelName::where('id',1)->get(['id', 'name']);
Haritsinh Gohil
  • 5,818
  • 48
  • 50
10

To get the result of specific column from table,we have to specify the column name.

Use following code : -

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();  

for example -

$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();  
Community
  • 1
  • 1
Jitender Sharma
  • 141
  • 1
  • 5
8
use App\Table;
// ...
Table::where('id',1)->get('name','surname');

if no where

Table::all('name','surname');
8

If you want to get a single value from Database

    Model::where('id', 1)->value('name');
Ali Raza
  • 135
  • 1
  • 10
6

Also you can use pluck.

Model::where('id',1)->pluck('column1', 'column2');
bereket gebredingle
  • 12,064
  • 3
  • 36
  • 47
  • 7
    Note that `pluck()` is less efficient than the other methods discussed because it doesn't modify the `SELECT ...` query, but rather, it operates on the already-returned result set. – Ben Johnson Aug 07 '18 at 12:52
4

You can use Table::select ('name', 'surname')->where ('id', 1)->get ().

Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.

Josh Rumbut
  • 2,640
  • 2
  • 32
  • 43
4

You can get it like

`PostModel::where('post_status', 'publish')->get(['title', 'content', 'slug', 'image_url']`)

link

3

If you want to get single row and from the that row single column, one line code to get the value of the specific column is to use find() method alongside specifying of the column that you want to retrieve it.

Here is sample code:

ModelName::find($id_of_the_record, ['column_name'])->toArray()['column_name'];
Brane
  • 3,257
  • 2
  • 42
  • 53
3

If you need to get one column calling pluck directly on a model is the most performant way to retrieve a single column from all models in Laravel.

Calling get or all before pluck will read all models into memory before plucking the value.

Users::pluck('email');
Hemerson Varela
  • 24,034
  • 16
  • 68
  • 69
2

you can also used findOrFail() method here it's good to used

if the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these method not give a 500 error..

ModelName::findOrFail($id, ['firstName', 'lastName']);
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
2

While most common approach is to use Model::select, it can cause rendering out all attributes defined with accessor methods within model classes. So if you define attribute in your model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get the user's first name.
     *
     * @param  string  $value
     * @return string
     */
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
}

And then use: TableName::select('username')->where('id', 1)->get();

It will output collection with both first_name and username, rather than only username.

Better use pluck(), solo or optionally in combination with select - if you want specific columns.

TableName::select('username')->where('id', 1)->pluck('username');

or

TableName::where('id', 1)->pluck('username'); //that would return collection consisting of only username values

Also, optionally, use ->toArray() to convert collection object into array.

Nikola Kirincic
  • 3,651
  • 1
  • 24
  • 28
2

For getting multiple columns (returns collection) :

Model::select('name','surname')->where('id', 1)->get();

If you want to get columns as array use the below code:

Model::select('name','surname')->where('id', 1)->get()->toArray();

If you want to get a single column try this:

Model::where('id', 1)->first(['column_name'])->column_name;
Shinoy p b
  • 353
  • 3
  • 13
1

->get() much like ->all() (and ->first() etc..) can take the fields you want to bring back as parameters;

->get/all(['column1','column2'])

Would bring back the collection but only with column1 and column2

Robert Pounder
  • 1,490
  • 1
  • 14
  • 29
0

You can use the below query:

Table('table')->select('name','surname')->where('id',1)->get();
Salman Zafar
  • 3,844
  • 5
  • 20
  • 43
Luis
  • 1
  • 1
0

If you wanted to get the value of a single column like 'name', you could also use the following:

Table::where('id', 1)->first(['name'])->name;
Faridul Khan
  • 1,741
  • 1
  • 16
  • 27
0

to get data from specific column use value

    $variable = DB::table('tbl_name')->where('column', '=',  $passedvariable)->value('column');
It's VIN
  • 152
  • 7