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?
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.
$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.
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.
You can do it like this:
Table::select('name','surname')->where('id', 1)->get();
Table::where('id', 1)->get(['name','surname']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With