【发布时间】:2016-06-29 18:59:24
【问题描述】:
我正在尝试将两个变量(帖子和答案)传递给 question.blade 视图,因为我在将正文、优点和缺点存储在数据库中时单击了“提交”按钮。 我收到以下错误:
试图获取非对象的属性(查看:D:\wamp\www\xxxxxxxxxx\resources\views\Question.blade.php) 在 9e68b64a739caa46ec7f5af26c6c40a6cf68ebf3.php 第 9 行 在 CompilerEngine->handleViewException(object(ErrorException), '1') 在 PhpEngine.php 第 44 行
控制器代码:
public function postAnswer(Request $request, $post_id)
{
$post = Post::where('id', $post_id)->first();
$body = $request['body'];
$pros = $request['pros'];
$cons = $request['cons'];
$answer = new Answer();
$answer->body = $body;
$answer->pros = $pros;
$answer->cons = $cons;
$request->user()->answers()->save($answer);
$post->answers()->save($answer);
return view('Question', [
'post' => $post ,
'answer' => $answer]);
question.blade 代码:
@foreach ($answer as $answers)
<p>{{ $answers->body }}</p>
<p>{{ $answers->pros }}</p>
<p>{{ $answers->cons }}</p>
@endforeach
【问题讨论】:
-
您不能在 foreach 上使用 $answer。只需删除 foreach 并使用 $answer 获取属性。
-
谢谢,成功了。但就我而言,一个问题有很多答案,我需要在答案表中循环?
-
然后你想循环遍历 $post->answers ......
-
当我使用 $post->answers 时,没有出现错误,但 question.blade 视图中没有显示任何内容,尽管有与此问题相关的答案。有什么想法吗?