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?

sigmaxf
  • 7,998
  • 15
  • 65
  • 125
  • `public function hasPass(){ if($this->password){ return $this; } return null; }` and then `$user = Auth::user()->hasPass();` then `if($user !== null)` – MozzieMD Aug 30 '15 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 . – scott Aug 31 '15 at 06:03

1 Answers1

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.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • I don't understand `$appends`. Does it mean the accessor will be appended to the model's attributes? – user2094178 Aug 30 '15 at 19:28
  • Yes. It will be appended to the rest of the model attributes when the model is serialized. – Joseph Silber Aug 30 '15 at 20:19
  • Ok, that being said, if I don't use `$appends`, the accessor will be available *only* in the object or collection. Is this correct? – user2094178 Aug 30 '15 at 20:28
  • Yes. Without the `$appends`, you can still access `$user->has_password`. – Joseph Silber Aug 30 '15 at 21:20
  • @Joseph Silber. i am facing same problem.if you know answer.can you post it to http://stackoverflow.com/questions/31934494/how-to-login-using-github-facebook-gmail-and-twitter-in-laravel-5-1 – scott Aug 31 '15 at 06:39