【问题标题】:Trying to get property 'user_name' of non-object: trting to get data of a single row in single page试图获取非对象的属性“用户名”:试图在单页中获取单行的数据
【发布时间】:2021-04-17 06:17:11
【问题描述】:

这是我的控制器页面

public function getsinglepost($slug)
          {  
                $post = User::where('slug', $slug)->get();
                $post_1 = DB::select('select * from user_post');
                $name = request()->input('user_name');
                $email = request()->input('user_email');
                $question = request()->input('user_question');
                 return view('single')
                               ->with('user_name',$post_1->user_name)
                               ->with('user_email',$post_1->user_email)
                               ->with('user_question',$post_1->user_question)
                               ->with(['post_1'=>$post_1])  
  }

这是我的迁移

*/
    public function up()
    {
        Schema::create('user_post', function (Blueprint $table) {
            $table->increments('id');
            $table->string('user_name',100);
            $table->string('user_email',100);
            $table->string('user_question',900);
            $table->string('slug',900);
            $table->timestamp('created_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_post');
    }
}

在这里,我试图获取不同页面中单行的数据,这让我很不爽 请随意添加任何内容

【问题讨论】:

  • 你想用这条线做什么$post_1 = DB::select('select * from user_post');
  • DB::select 返回数组,而不是对象。

标签: php laravel error-handling eloquent controller


【解决方案1】:

问题是你使用了 $request 对象并且你只在你的函数中传递了 $slug。

你的代码应该是这样的:

public function getsinglepost(Request $request, $slug)
{
    // Your code
}

我认为这会奏效。

【讨论】:

    【解决方案2】:

    我认为您的查询是错误的。我认为您的需要是根据 user_post 表上的 slug 列获取用户数据

    也许这会起作用:

    public function getsinglepost($slug)
    {  
          $post = DB::table('user_post')->where('slug', $slug)->first();
          return view('single', ['post' => $post]);
          // or like this
          return view('single', compact('post'));
    }
    

    那么在你看来:

    <table>
    <tr>
        <td>User name</td>
        <td>{{ $post->user_name }}</td>
    </tr>
    <tr>
        <td>Email</td>
        <td>{{ $post->user_email }}</td>
    </tr>
    <tr>
        <td>Question</td>
        <td>{{ $post->user_question }}</td>
    </tr>
    

    【讨论】:

    • 这对我来说很好......非常感谢:)
    • 没问题,如果这对您有帮助,您能否将其标记为已回答?
    猜你喜欢
    • 2021-09-03
    • 2019-05-23
    • 2019-07-11
    • 2014-12-09
    相关资源
    最近更新 更多