1

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?

2
  • public function hasPass(){ if($this->password){ return $this; } return null; } and then $user = Auth::user()->hasPass(); then if($user !== null) Commented Aug 30, 2015 at 16:45
  • @raphadko.i am also facing problem in socialite.how you authenticate facebook user.i mean laravel auth require email and password but in facebook we get only email . Commented Aug 31, 2015 at 6:03

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't understand $appends. Does it mean the accessor will be appended to the model's attributes?
Yes. It will be appended to the rest of the model attributes when the model is serialized.
Ok, that being said, if I don't use $appends, the accessor will be available only in the object or collection. Is this correct?
Yes. Without the $appends, you can still access $user->has_password.
@Joseph Silber. i am facing same problem.if you know answer.can you post it to stackoverflow.com/questions/31934494/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.