CMOS
CMOS

Reputation: 2907

Laravel eloquent add custom query elements

So I am having some trouble with size and server requests. So I am trying to get a minified version of a row from eloquent. So for example here is my query call

$user = User::where('email', '=', '[email protected]')->first();

This works but returns a ton of information. Stuff that I do not need, relations, observables, dates, guarded status, fillable AND every single column. This is expected so If I want to get first and last name and email. I could do something like this

$users = DB::table('users')->select('firstname','lastname', 'email')->get();

And this would work, except I don't want to type that every single time I wanna do this. Is it possible for me to setup somewhere in eloquent or in my model so that I can do

$user = User::where('email', '=', '[email protected]')->min()->first();

Simply add a custom function called min() that only grabs those three values. Is something like this possible?

Upvotes: 5

Views: 15688

Answers (3)

pespantelis
pespantelis

Reputation: 15372

You can insert the $hidden array at your model, with the columns that you don't want to appear.

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

Yes, you can do it if you declare a method in your User model like this:

// User.php
public function scopeMin($query)
{
    return $query->select('firstname','lastname', 'email');
}

Then you can use it like this (To get only 'firstname','lastname', 'email'):

$user = User::where('email', '=', '[email protected]')->min()->first();

Read about Query Scope on the documentation.

Upvotes: 7

bgallagh3r
bgallagh3r

Reputation: 6086

You can limit the columns by passing an array in the first() method.

$user = User::where('email', '=', '[email protected]')->first(['firstname','lastname', 'email']);

Upvotes: 4

Related Questions