【问题标题】:Laravel 8: Trying to get property 'name' of non-object while returning resultsLaravel 8:在返回结果时尝试获取非对象的属性“名称”
【发布时间】:2021-07-10 05:30:07
【问题描述】:

我正在使用 Laravel 8 开发我的在线论坛项目。

这是我到/uri的路线:

Route::get('/', function () {
    $threads = App\Models\Thread::paginate(15);
    return view('welcome', compact('threads'));
});

welcomeblade:

@section('content')
    @include('thread.partials.thread-list')
@endsection

thread-list,我添加了这个:

@forelse($threads as $thread)
Posted by <a href="{{route('user_profile',$thread->user->name)}}">{{$thread->user->name}}</a> {{$thread->created_at->diffForHumans()}}
@endforelse

但不知怎的,我得到了这个错误:

ErrorException 试图获取非对象的属性“名称”(查看:thread-list.blade.php)

那么这里出了什么问题?我该如何解决这个问题?

非常感谢你们的任何想法或建议......

提前致谢。

【问题讨论】:

  • 您正在尝试从用户访问名称,但用户不只是线程表中的一个字段吗?比如id?
  • 在您的问题中添加您的模型关系代码和数据库文件名。

标签: php laravel laravel-8


【解决方案1】:

这是因为 $thread->user 为 null 表示正在删除用户。 您可以使用以下方式之一:

  1. 整理出Controller中不存在用户的线程:

    Route::get('/', function () { $threads = App\Models\Thread::has('user')->paginate(15); 返回视图(“欢迎”,紧凑(“线程”)); });

  2. 如果用户不存在则删除标签:

    @forelse($threads 作为 $thread) 发表者 @if($thread->user) 用户->名称)}}">{{$thread->用户->名称}} @别的 匿名的 @万一 {{$thread->created_at->diffForHumans()}} @endforelse

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2021-06-05
    • 2021-07-29
    • 2019-12-13
    • 1970-01-01
    • 2016-04-15
    • 2019-04-23
    • 2020-09-28
    相关资源
    最近更新 更多