mertindervish
mertindervish

Reputation: 301

How to select users except roles with Laravel Eloquent

I need to select only id and name attribute from users table except roles attribute. I tried this:

$school_user = User::select('name', 'id')->get()->toArray();

but when I print it to screen it returns array with his roles. Like this:

Array
(
    [0] => Array
        (
            [name] => Admin
            [id] => 1
            [roles] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => admin
                            [pivot] => Array
                                (
                                    [user_id] => 1
                                    [role_id] => 1
                                )

                        )

                )

        )

)

Any suggestions to get only name and id attributes except roles?

There is my User Model class (a bit cleaned):

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    protected $fillable = array('email', 'name', 'password', 'block');
    protected $guarded = array('id');

    /**
     * Get the schools or kindergardens a user can moderate
     */
    public function schools()
    {
        return $this->belongsToMany('School', 'school_user');
    }

    /**
     * Get the roles a user has
     */
    public function roles()
    {
        return $this->belongsToMany('Role', 'users_roles');
    }

    /**
     * Find out if User is an employee, based on if has any roles
     *
     * @return boolean
     */
    public function isEmployee()
    {
        $roles = $this->roles->toArray();
        return !empty($roles);
    }

    /**
     * Find out if user has a specific role
     *
     * $return boolean
     */
    public function hasRole($check)
    {
        return in_array($check, array_fetch($this->roles->toArray(), 'name'));
    }

    /**
     * Get key in array with corresponding value
     *
     * @return int
     */
    private function getIdInArray($array, $term)
    {
        foreach ($array as $key => $value) {
            if ($value['name'] == $term) {
                return $key;
            }
        }

        throw new UnexpectedValueException;
    }

    /**
     * Add roles to user to make them a concierge
     */
    public function makeEmployee($role_id)
    {
        $assigned_roles = array();

        $roles = Role::all()->keyBy('id')->toArray();

        $this->roles()->attach(array($role_id));
    }

    public $invitation;

    protected static function boot()
    {
        parent::boot();

        static::creating(function($model)
        {
            $data = array(
                'invitation' => $model->invitation,
                'email' => $model->email,
                'name' => $model->name,
                'password' => $model->password
            );

            $model->password = Hash::make($model->password);

            $rules = array(
                'invitation' => 'required',
                'email' => 'unique:users,email|required|email',
                'name' => 'required|min:3|max:20',
                'password' => 'required|min:8|max:30'
            );
            $validator = Validator::make($data, $rules);

            if ($validator->fails()) {
                throw new ValidationException(null, null, null, $validator->messages());
            } else {                
                return $model->validate();
            }
        });

        static::created(function($model)
        {
            $role_id = Invitation::where('code', '=', $model->invitation)->first()->role_id;
            $model->makeEmployee($role_id);
            $invitation_code = Invitation::where('code', '=', $model->invitation)->update(array('used_by' => $model->id));
        });
    }

    public function validate()
    {
        if (is_null(Invitation::where('code', '=', $this->invitation)->where('used_by', '=', '0')->first())) {
            throw new ValidationException(null, null, null, array('invitation' => "Грешен код."));
        } else {
            return true;
        }
    }

    public function updatePass($old_password, $new_password, $repeat_new_password)
    {
        $data = array(
            'old_password' => $old_password,
            'new_password' => $new_password,
            'repeat_new_password' => $repeat_new_password
        );

        $rules = array(
            'old_password' => 'required',
            'new_password' => 'required|min:8|max:30',
            'repeat_new_password' => 'required|same:new_password'
        );

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            throw new ValidationException(null, null, null, $validator);
        } else {
            $user = User::find(Auth::user()->id);

            if (Hash::check($old_password, $user->password)) {
                $user->password = Hash::make($new_password);

                if($user->save()) {
                    return true;
                } else {
                    throw new ValidationException(null, null, null, array('mainError' => "Грешка с базата данни."));
                }
            } else {
                throw new ValidationException(null, null, null, array('old_password' => "Моля въведете правилно страта Ви парола."));
            }
        }
    }

    public function login($email, $password, $remember)
    {
        $data = array(
            'email' => $email,
            'password' => $password
        );

        $rules = array(
            'email' => 'required|email',
            'password' => 'required'
        );

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            throw new ValidationException(null, null, null, $validator);
        } else {
            if (User::where('email', '=', $email)->first()->block == true) {
                throw new ValidationException(null, null, null, array('mainError' => "Акаунтът ви е блокиран."));
            } else {
                $remember = ($remember) ? true : false;
                if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
                    return true;
                } else {
                    throw new ValidationException(null, null, null, array('mainError' => 'Имейлът или паролата е грешна.'));
                }
            }
        }
    }
}

And Role Model:

<?php

class Role extends Eloquent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'roles';

    protected $fillable = array('name');
    protected $guarded = array('id');


    /**
     * Set timestamps off
     */
    public $timestamps = false;

    /**
     * Get users with a certain role
     */
    public function users()
    {
        return $this->belongsToMany('User', 'users_roles');
    }
}

I'm sorry for use of bulgarian language in exceptions

Upvotes: 2

Views: 3209

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

Looking at the code it's rather not possible that running just:

$school_user = User::select('name', 'id')->get()->toArray();

make appending roles to result.

You should make sure that you don't add anything to $appends property and you don't load relationship somewhere in your code. You should also make sure that you don't have custom toArray() method implemented that loads this relationship when converting to array. If you are sure you don't you should show the full code and your exact Laravel version.

EDIT

You didn't show where you launch your code with select or lists however you load your roles relationship in many methods - for example isEmployee, isEmployee or hasRole. That's why roles are used when you are converting to array. You might want to write your custom toArray method to remove roles from your result set when converting to array.

Upvotes: 1

Related Questions