我正在写博客,学习如何使用laravel。博客基本上已经完成了,但我仍然在代码中发现了一些错误。大多数问题都解决了,但还有一个错误我无法修复。
这是关于用户的"我的线程"。如果用户创建了一个新帐户,他还会得到一个"我的线程"页面。如果他在翻页,他会看到所有的线索。我现在的问题是,如果他没有任何线程,他会得到一个:
正在尝试获取非对象异常的属性。我当然不想让他看到这些。
所以这是我的控制器中的函数到他的"我的线程"页面:
public function startpage($id)
{
// $userthreads = Thread::query()->where('user_id', $id)->get();
// return $userthreads;
try {
return view('test.startpage', [
'userthreads' => Thread::query()->where('user_id', $id)->get(),
'user' => User::query()->findOrFail($id)
]);
} catch (ModelNotFoundException $e) {
return view('test.notfound');
}
}
对于前两行(未注释(,我检查了数组中是否有内容。我刚拿到
'[]'
作为输出。这意味着数组为空。我将$userthreads变量返回到视图中,在我的视图中,我这样做是为了避免问题:
@if(empty($userthreads))
<a href="{{ action('Test''TestController@add') }}">Add Thread </a>
@else
@foreach($userthreads as $uthread)
<ul>
<a href="{{ action('Test''TestController@show', [$uthread->id]) }}">{{$uthread->thread}}</a>
</ul>
@endforeach
@endif
这对我不起作用,我不明白为什么。也许你们中的某个人可以在那里帮我。
谢谢你的帮助!
阿列克谢·梅泽宁的当前代码回答:
public function startpage($id)
{
try {
$arr = [];
$arr['userthreads'] = Thread::where('user_id', $id)->get();
$arr['user'] = User::findOrFail($id);
return view('test.startpage', $arr);
} catch (ModelNotFoundException $e) {
return view('test.notfound');
}
}
HTML:
@if(count($userthreads) > 0)
<a href="{{ action('Test''TestController@add') }}">Thread hinzufügen</a>
@else
@foreach($userthreads as $uthread)
<ul>
<a href="{{ action('Test''TestController@show', [$uthread->id]) }}">{{$uthread->thread}}</a>
</ul>
@endforeach
@endif
错误:
Trying to get property of non-object (View: /var/www/laravel/logs/resources/views/test/startpage.blade.php)
好的,我们在聊天中讨论过,发现了一个问题:
@if(Auth::user()->id == $userthreads->first()->user_id)
错误出现在起始页.blade.php此处
@if( Auth::user()->id == $userthreads->first()->user_id)
并将其更改为低于
@if( isset($userthreads) && count($userthreads) > 0 && Auth::user()->id == $userthreads->first()->user_id)
就是
@if(isset($userthreads) && count($userthreads) > 0)
@foreach($userthreads as $uthread)
<ul>
<a href="{{ action('Test''TestController@show', [$uthread->id]) }}">{{$uthread->thread}}</a>
</ul>
@endforeach
@else
<a href="{{ action('Test''TestController@add') }}">Thread hinzufügen</a>
@endif
@ItzMe488我认为替换以下代码:
@if( Auth::user()->id == $userthreads->first()->user_id)
带有
@if( Auth::user()->id == $user->first()->user_id)
应该在没有任何错误和bug的情况下工作。
解释:
在我们的聊天中,@AlexeyMezenin发现错误是因为$userthreads
为空,$userthreads->first()
因此出错。我认为,由于您也将$user
传递到模板中,使用它我们可以为当前用户进行身份验证,这应该可以防止用户B在用户A的页面中创建线程。