【问题标题】:Weird Problem: Trying to get property 'name' of non-object in Laravel Blade奇怪的问题:试图在 Laravel Blade 中获取非对象的属性“名称”
【发布时间】:2021-06-30 12:14:21
【问题描述】:

我有四个表:用户、国家、地区和乡镇。

在 User.php 模型中,

public function country() {
    return $this->belongsTo(Country::class, 'country_id');
}

public function region() {
    return $this->belongsTo(Region::class, 'region_id');
}

public function township() {
    return $this->belongsTo(Township::class, 'township_id');
}

在 Country.php、Region.php 和 Township.php 模型中,

public function users() {
    return $this->hasMany(User::class);
}

在 users.blade 中,我尝试打印用户的位置

{{ $user->township->name }}, {{ $user->region->name }}, {{ $user->country->name }}

而且,我得到了Trying to get property 'name' of non-object 异常。

当我尝试像{{ $user->township->name }}, {{ $user->region->name }}, {{ $user->country->name }} 一样打印country、region 和township 时,它打印如下-

{"id":1,"region_id":1,"name":"Hlaing"}, {"id":1,"country_id":1,"name":"Yangon"}, {"id":1,"name":"Myanmar"}

只在远程服务器出现这个异常,在本地机器没有问题。

我为所有用户、已批准用户和待定用户提供三个视图。我有 users.blade.php、users_approved.blade.php 和 users_pending.blade.php。这些刀片是相似的,只有标题文本不同。批准的用户视图没有问题(远程服务器也是)。

在 MainController.php 中,我有这些功能 -

function users(Request $request) {
    $users = User::all();

    return view('users', [ 'users' => $users ]);
}

function users_approved(Request $request) {
    $users = User::where('approval_status', 'APPROVED')->get();

    return view('users_approved', [ 'users' => $users ]);
}

function users_pending(Request $request) {
    $users = User::where('approval_status', 'PENDING')->get();

    return view('users_pending', [ 'users' => $users ]);
}

我已经尝试过 - php artisan view:clear、php artisan cache:clear、php artisan config:clear。

【问题讨论】:

  • 您是否确保所有用户实际上拥有所属的乡镇、国家和地区?

标签: php mysql laravel laravel-blade


【解决方案1】:

如果您的问题只出现在远程机器上,可能是因为那里存储的数据不同。特别是,对于某些用户而言,由于某些原因(遗留记录、代码错误、未使用事务...等),他们的某些关系可能没有设置。

Eloquent docpage itself 建议的一种解决方法是为那些绑定模型提供默认值,当数据库中缺少关系时使用。例如:

public function country() {
    return $this->belongsTo(Country::class, 'country_id')->withDefault([
      'name' => 'Country Not Set',
    ])
}

public function region() {
    return $this->belongsTo(Region::class, 'region_id')->withDefault([
      'name' => 'Region Not Set',
    ])
}

... 等等。另一种选择是运行数据库查询以获取远程机器上的所有用户,条件如下:

WHERE country_id IS NULL 
   OR region_id IS NULL 
   OR township_id IS NULL

根据您的需要,您可以修改这些记录或以一种或另一种方式禁用它们。

【讨论】:

  • 你是绝对正确的!当我检查用户列表时,有一个待处理用户的 township_id = NULL。非常感谢!
猜你喜欢
  • 2019-12-13
  • 2020-03-28
  • 2021-06-04
  • 2018-06-27
  • 2020-10-23
  • 2020-09-28
  • 2019-03-27
  • 2021-09-03
  • 2019-05-23
相关资源
最近更新 更多