我使用Laravel 8,用戶模型與模型UserProfile有關系
。
如下所示
class User extends Authenticatable
{
使用 LaratrustUserTrait。
使用 HasApiTokens;
使用 HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
.
.
.
public function profile(){
return $this->hasOne(UserProfile::class,'user_id')。
}
當我創建一個新的用戶時,我直接為他做登錄并將他重定向到儀表板 如下所示
Auth::login($user, true)。
return $this-> sendSuccessResponse()。
但我的問題是,我如何在刀片或控制器中使用用戶資料和它的userProfile關系? 我試圖在刀片中使用以下代碼
<img src="{{Auth:: user()->profile->image}}" id="profile-img" alt=">
但我得到了以下錯誤資訊
試圖在null上讀取屬性 "image"
。uj5u.com熱心網友回復:
你的profile關系要么是畸形的,要么是缺失的。
這個錯誤意味著你試圖在一個null的值上獲取屬性image。
這是因為Auth::user()->profile回傳null,那么Auth::user()->profile->image就像寫(null)->image。
這可能是由幾個方面造成的:
這可能是由幾個方面造成的。
- 資料庫中的資料缺失 錯誤的列名。
- 錯誤的表名 。
繞過這個錯誤最簡單的方法是只在這個關系不是null時顯示圖片:
@if(Auth::user()->profile !== null)
<img src="{{Auth:: user()->profile->image}}" id="profile-img" alt=">
@endif
然而,最好是了解它為什么是null,至少可以避免在你的專案中出現進一步的問題。
uj5u.com熱心網友回復:
在你的用戶模型中應用這些變化。我想它會對你有用的。
用戶模型
用戶模型
標籤:class User extends Authenticatable
{
/**。
*應該總是被加載的關系。
*
* @var陣列
*/
protected $with = ['file']。
/**。
*獲取用戶資料。
*/
public function profile()
{
return $this->hasOne(UserProfile::class)。
}
}
