Laravel 5.7通过一对一关系的用户配置文件获取当前登录的用户

时间:2019-02-19 10:31:14

标签: laravel-5.7 laravel-passport

我目前正在学习Laravel 5.7。我已经从github下载了源代码。在该代码中,我已经实现了与用户和个人资料表的一对一关系。

我已经能够成功登录用户,并能够注册用户。但是,当我调用方法getCurrentUser()时,它仅返回用户表中的数据,而不返回概要文件中的数据。

User Model

class AuthController extends Controller
{
    public function __construct()
   {
     $this->middleware('auth:api')->only('logout');
   }
   public function getCurrentUser(): User
   {
     return request()->user();
   }
    public function login(Request $request): JsonResponse
   {
    $credentials = $this->validate($request, [
        'email'    => 'required|email|exists:users',
        'password' => 'required|min:5',
    ]);

    if (auth()->attempt($credentials)) {
        $user = auth()->user();
        /** @var User $user */
        $user['token'] = $this->generateTokenForUser($user);

        return response()->json($user);
    } else {
        return response()->json(['success' => 'false', 'message' => 'Authentication failed'], 401);
    }
 }

}

User

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name','last_name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * Encrypt the password while savinf it.
     *
     * @param string $password
     */
    public function setPasswordAttribute(string $password)
    {
        $this->attributes['password'] = Hash::make($password);
    }
    public function User()
    {
        return $this->hasOne('App\UserProfile');
    }

}

User Profile

class UserProfile extends Model
{
    //
        /**
     * The following fields are mass assignable.
     * @var array
     */
    protected $fillable = ['first_name', 'last_name', 
    'middle_name', 'date_of_birth', 'nationality','phone','image','permanent_address_country',
    'permanent_address_state','permanent_address_district','temp_address_district','temp_address_state','gender','user_id'];

    public function UserProfile()
    {
        return $this->belongsTo('App\User');
    }
}

如何通过Auth getCurrentUser API返回当前登录的用户和个人资料详细信息?

我在客户端使用Vue.js

1 个答案:

答案 0 :(得分:4)

在您的User模型中,将User()方法更改为此:

public function userProfile()
{
    return $this->hasOne('App\UserProfile');
}

然后在您的UserProfile模型中,将UserProfile()方法更改为:

public function user()
{
    return $this->belongsTo('App\User');
}

然后您可以通过此查询获取用户及其个人资料:

User::with('userProfile')->find(Auth::id()); 

根据您的情况,您可以将getCurrentUser()方法重构为:

use Illuminate\Http\Request;

public function getCurrentUser(Request $request): User
{
    return $request->user()->load('userProfile');
}