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

问题描述 投票:0回答:1

我正在学习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');
    }
}

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

我在客户端使用getCurrentUser

laravel-5.7 laravel-passport
1个回答
4
投票

在你的Vue.js模型中,将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()
© www.soinside.com 2019 - 2024. All rights reserved.