Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select specific columns in laravel eloquent

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?

like image 700
devnull Ψ Avatar asked Oct 10 '22 11:10

devnull Ψ


People also ask

How to get specific columns in Laravel eloquent?

Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.

How do you pluck in laravel?

$users = User::all()->pluck('username'); You can also use pluck() method on nested objects like relationships with dot notation. Laravel Pluck method can be very useful when you extract certain column values without loading all the columns. You can benefit from the Laravel pluck method in the blade views as well.

What is laravel eloquent query?

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table.


2 Answers

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();
like image 361
Marcin Nabiałek Avatar answered Oct 12 '22 00:10

Marcin Nabiałek


Table::where('id', 1)->get(['name','surname']);
like image 125
Utkarsh Pandey Avatar answered Oct 12 '22 01:10

Utkarsh Pandey