Quick snippet – Selecting only certain columns for a model in laravel

With a model named (Person) that maps to a table named (persons) with a structure defined below

CREATE TABLE `persons` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `first_name` VARCHAR(255) NOT NULL,
  `last_name` VARCHAR(255)  NOT NULL,
  `email` VARCHAR(255) NOT NULL,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `persons` (`email`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Then, Consider the eloquent statement given below

$result = Person::find(1);

this is equivalent to,

SELECT * FROM Persons

The above can be wasteful if all you require is just a few columns such as the firstname and lastname, to fix this, we use the eloquent statement below

$result = Person::find(1, ['first_name', 'last_name']);

This is equivalent to,

SELECT first_name, last_name FROM persons

Hope, you have been able to learn something new today.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s