sehmbimanvir's avatar

Eloquent Select Default Columns

I have a User Model with columns id, name, email, uuid, password,address,state,city,timestamps

What i am doing is

User::select('id', 'name', 'email', 'uuid')->find(1);

Problem

Now the problem is that every time i am querying on this model i have to specify columns because i don't need other columns (in most cases).

Question

Is there any method by which i can select columns by default. So that every time when i call user model it will load basic columns id, name, email, uuid automatically. ?

0 likes
7 replies
rin4ik's avatar

in your User model u can specify hidden variable with fields you don't want to show.

protected $hidden = [
        'password',
        'remember_token']

now

$user = User::find(1);
1 like
Reppair's avatar

@rin4ik $hidden affects what is shown after seriallization. Not the selected columns in the query.

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<string>
     */
    protected $hidden = [];

However, using a global scope, to specify default columns to be selected totally does the trick. :)

Cheers!

1 like
click's avatar

Just a thought, could you do this with the use of scopes? https://laravel.com/docs/5.6/eloquent#query-scopes

# User.php
public function scopeMySelect($builder)
{
    $builder->select(['id', 'name', 'email', 'uuid']);
}

# and use it like:
User::where('email', '[email protected]')->mySelect()->first();

Or with the use of global scopes:

# User.php
public static function boot()
{
    static::addGlobalScope('mySelect', function ($builder) {
        $builder->select(['id', 'name', 'email', 'uuid']);
    });
}

# and use it like:
User::where('email', '[email protected]')->first();
# or without the scope:
User::withoutGlobalScope('mySelect')->where('email', '[email protected]')->first();

the solution of @rin4ik is probably easier ;-)

5 likes
0xlaradev's avatar

@click Maybe I was doing something wrong (or has something to do that I'm using Laravel 11), but I had to add "parent::boot();" before "static::addGlobalScope" like this so that it would work:

# User.php
public static function boot()
{
	parent::boot();
    static::addGlobalScope('mySelect', function ($builder) {
        $builder->select(['id', 'name', 'email', 'uuid']);
    });
}
sehmbimanvir's avatar

@rin4ik But i don't want to use getHidden() method every time when i select state, city.

I just want to select basic columns so i don't need to select in query.

My User table contains almost 30-32 fields and i don't want to select them all

Vilfago's avatar

it was in fact addSelect and not select. Thus, you can add another ->select to add some fields.

# User.php
public function scopeMySelect($builder)
{
    $builder->addSelect(['id', 'name', 'email', 'uuid']);
}

# and use it like:
User::where('email', '[email protected]')->mySelect()->first();
2 likes

Please or to participate in this conversation.