关于我的问题有很多问题,但我从未遇到过这种情况,所以这里是我的代码:
<td>{{ $note->title}}</td>
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->created_at)) }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->updated_at)) }}</td>
到目前为止一切正常,除了
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
我发现问题是 $note->user
并且它抛出了
(2/2) ErrorException Trying to get property of non-object
这对我来说没有任何意义,因为上面的 $note->title
和 $note->created_at
就像魅力一样。有什么想法吗?
最佳答案
您应该始终检查用户是否存在:
$user = App\User::where('id', $note->user)->first();
然后在 View 中:
{{ is_null($user) ? 'No user with specified ID' : $user->name }}
此外,在 View 中使用 Eloquent 是一个糟糕的主意。
关于php - 尽管在同一个地方工作,但尝试在 Laravel 中获取非对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45117115/