I’m working with Laravel 8 to develop my project which is an Online Forum.
And here is my route to /
uri:
Route::get('/', function () { $threads = AppModelsThread::paginate(15); return view('welcome', compact('threads')); });
And at welcome
blade:
@section('content') @include('thread.partials.thread-list') @endsection
And at thread-list
, I added this:
@forelse($threads as $thread) Posted by <a href="{{route('user_profile',$thread->user->name)}}">{{$thread->user->name}}</a> {{$thread->created_at->diffForHumans()}} @endforelse
But somehow I get this error:
ErrorException Trying to get property ‘name’ of non-object (View: thread-list.blade.php)
So what is going wrong here ? How can I fix this issue ?
I would really appreciate any idea or suggestion from you guys…
Thanks in advance.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This is because $thread->user is null which mean the user is being deleted.
you can use one of the following ways:
-
sort out the thread which user not exists in Controller:
Route::get(‘/’, function () {
$threads = AppModelsThread::has(‘user’)->paginate(15);
return view(‘welcome’, compact(‘threads’));
}); -
remove a tag if user not exists:
@forelse($threads as $thread)
Posted by
@if($thread->user)
user->name)}}”>{{$thread->user->name}}
@else
anonymous
@endif
{{$thread->created_at->diffForHumans()}}
@endforelse
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0