sigmaxf
sigmaxf

Reputation: 8492

Check if the user has a password in laravel

I have two ways of registering into my website: email or facebook login.

On facebook login, the user doesn't get a password. Which I need to read in some cases to know if the user will have to type the password to change their email for example

I want to, when returning the user object in laravel, also return a property has_pass that would keep this value.. Instead of creating a new database field, I just thought of using a function in the user model to determine if the password is blank, like this:

public function hasPass(){
    if($this->password){
        return true;
    }
    return false;
}

This works OK, but I want the data to return with the user object, so I can just check $user->haspass property, instead of having to call the function hasPass() at every check. So, how can I do it and is this a good way to do it?

Upvotes: 1

Views: 1592

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219936

Use an accessor for has_password:

class User extends Eloquent
{
    protected $appends = ['has_password'];

    public function getHasPasswordAttribute()
    {
        return ! empty($this->attributes['password']);
    }
}

Adding it to the $appends property will automatically add has_password to the array when the model is serialized.

Upvotes: 5

Related Questions