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?
You can use the below query:
->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
andcolumn2
By using all() method we can select particular columns from table like as shown below.
Note: Laravel 5.4
You can also use
find()
like this:The
$id
variable can be an array in case you need to retrieve multiple instances of the model.you can also used
findOrFail()
method here it's good to usedAlso you can use pluck.