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?
Use following code : -
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.
You can use get() as well as all()
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.
You can do it like this: