douzhuo8312 2018-08-07 09:56
浏览 44

如果可以在使用护照注册laravel api后自动登录

Register Api for Android App stored And Return the response Success. I want know If its possible to Automatically Login if Register Success We are using

php artisan make:auth

in Laravel Web

 public function signup(Request $request){

    try{
         $User = $request->all();
         if($request->has('referal_code')){
             $User['referal_code'] = $request->referal_code;
        }
         $User['password'] = bcrypt($request->password);
         $User['picture']  = 'http://lorempixel.com/100/100/';
         $User = User::create($User);
        return $User;
    }catch(Exception $e){
         return response()->json(['error' =>'api.something_went_wrong'], 500);
    }
 }
}

Login Api

  public function login(){ 
    if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
        $user = Auth::user(); 
        $success['token'] =  $user->createToken('MyApp')-> accessToken; 
        return response()->json(['success' => $success], $this-> successStatus); 
    } 
    else{ 
        return response()->json(['error'=>'Unauthorised'], 401); 
    } 
}
  • 写回答

1条回答 默认 最新

  • douye6812 2018-08-07 10:11
    关注

    You created the user so it returns an user_id, with the user_id you can login the user.

    Auth::loginUsingId($user_id);
    
    // Login and "remember" the given user...
    Auth::loginUsingId(1, true);
    

    Authenticate A User Instance

    Auth::login($user);
    
    // Login and "remember" the given user...
    Auth::login($user, true);
    

    https://laravel.com/docs/5.6/authentication#other-authentication-methods

    For Passport

    You can add findForPassport into User model:

    public function findForPassport($identifier) {
            return $this->orWhere('email', $identifier)->orWhere('username', $identifier)->first();
    }
    

    and add 'username' to $fillable

    protected $fillable = [
            'name', 'email', 'password', 'username'
    ];
    

    https://laracasts.com/discuss/channels/laravel/laravel-passport-login-using-username-or-email?page=1

    评论

报告相同问题?