Laravel eloquent add custom query elements

10,196

Solution 1

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.

Solution 2

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

$user = User::where('email', '=', '[email protected]')->first(['firstname','lastname', 'email']);
Share:
10,196
CMOS
Author by

CMOS

Updated on June 09, 2022

Comments

  • CMOS
    CMOS almost 2 years

    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?

  • The Alpha
    The Alpha over 9 years
    This is not what the OP asked for.
  • CMOS
    CMOS over 9 years
    Perfect! this is exactly what I wanted.
  • The Alpha
    The Alpha over 9 years
    Welcome @CalvinMoss :-)
  • Jarek Tkaczyk
    Jarek Tkaczyk over 9 years
    Only I wouldn't call it min, since there's already a method on the builder min(). And it will still return full object, just a few less fields.