gpt4 book ai didi

php - Laravel:试图获取非对象的属性

转载 作者:行者123 更新时间:2023-11-30 22:07:11 28 4
gpt4 key购买 nike

我一直在 Laravel 框架中编写 Web 应用程序,并且遇到了为用户获取某些数据时遇到的问题。我的 Web 应用程序的用户结构基于一个主用户表,然后我有一个 RP 表用于所有用户统计信息,例如健康、能量、他们拥有的元素等。

访问页面时我试图显示此数据我收到以下错误

Trying to get property of non-object (View: C:\workspace\mainwebsite\resources\views\frontend\home.blade.php)

O 只是尝试为用户打印出角色扮演表的 user_id 列(是的,我尝试了其他列,它们输出相同的结果)

<div class="panel panel-default">
<div class="panel-body">
{{ Auth::user()->roleplay->user_id }}
</div>
</div>

这是我的用户表类:

<?php
namespace App\Database\Website\User;

use Hash;
use Eloquent;
use \Illuminate\Auth\Authenticatable;
use \Illuminate\Contracts\Auth\Authenticatable as Authentication;

class Player extends Eloquent implements Authentication
{
use Authenticatable;

protected $primaryKey = 'id';
protected $table = 'users';
public $timestamps = false;
protected $fillable = [];

public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}

public function setUsernameAttribute($value)
{
return $this->attributes['username'] = $value;
}

public function roleplay()
{
return $this->hasOne('App\Database\Website\User\Roleplay', 'user_id');
}
}

这是我的角色扮演表类:

<?php
namespace App\Database\Website\User;

use Eloquent;

class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = ['user_id'];

public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}

}

最佳答案

检查以确保您当前的用户有一个roleplay 对象。 Eloquent 将为空关系返回 null

<div class="panel panel-default">
@if(Auth::user()->roleplay)
<div class="panel-body">
{{ Auth::user()->roleplay->user_id }}
</div>
@endif
</div>

问题:为什么不只获取授权用户的 ID ({{Auth::user()->id}})?无论如何,角色扮演对象似乎与该 ID 上的用户相关;为什么要通过关系来获取您已经拥有的 ID?

相关:

Laravel Blade template how to return null instead of ErrorException when trying to get property of non-object

关于php - Laravel:试图获取非对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41243460/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com