【问题标题】:Error Trying to get property of non-object in laravel尝试在 laravel 中获取非对象的属性时出错
【发布时间】: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 视图中没有显示任何内容,尽管有与此问题相关的答案。有什么想法吗?

标签: php laravel


【解决方案1】:

您将 $answer 作为单个对象发送,但在刀片中将其作为数组使用,或者尝试直接在刀片中使用它而不使用 @foreach,或者您实际上是在尝试发送一组答案,然后发送$request-&gt;user()-&gt;answers$post-&gt;answers

【讨论】:

  • 这将数据正确保存在数据库中。但是 question.blade 中没有出现任何内容,尽管有与此问题相关的答案....有什么想法吗?
  • $post-&gt;answers()$request-&gt;user()-&gt;answers() 将返回一个查询生成器。要获得答案,请使用$post-&gt;answers$request-&gt;user()-&gt;answers
【解决方案2】:

您需要传递'answer' =&gt; $request-&gt;user()-&gt;answers()-&gt;latest()-&gt;first(),而不是传递'answer' => $answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2019-09-11
    • 2021-10-06
    相关资源
    最近更新 更多