【问题标题】:ErrorException Trying to get property of non-object Laravel 5.4ErrorException 试图获取非对象 Laravel 5.4 的属性
【发布时间】:2017-08-30 11:08:04
【问题描述】:

这是我的 PostController 控制器:

public function getAllPosts() {
    $posts = Posts::all();

    /*foreach ($posts as $post){

        /* $username = $post->user->name;
        //do something with $username

    }*/

    return View::make('welcome', compact('posts'));
    //here the $detailed_posts can be defined in the 'do something' above
}

这是我的用户模型 Eloquent

代码
class User extends Eloquent {

    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    public function posts(){
        return $this->hasMany('App\Post');
    }

后模型雄辩

class Posts extends Eloquent {
    protected $table = 'posts';
    protected $fillable = array('title, image, text, user_id');
    public $timestamps = false;

    public function user(){
        return $this->belongsTo('App\User','user_id');
    }

这是我的welcome.blade.php

@foreach ($posts as $post)
<div class="col-sm-7">
<hr>
<h2>{{ $post->title}}</h2>
<h5>
    <span class="glyphicon glyphicon-time"></span> Post by {{$post->user->username}}, Sep 27, 2015.
</h5>
@endforeach

{{$post-&gt;user-&gt;username}} 出现错误

我已经尝试过使用{{$post-&gt;user['username']}},但没有显示任何用户价值。

有人可以在这个过程中帮助我吗?

【问题讨论】:

  • 错误声明非常清楚,正如您已经提到的 $post->user['username'] 有效。我假设这里 $post->user 返回一个数组而不是一个对象。看看你得到了什么 var_dump($post->user);
  • 只需检查所有帖子是否有 user_id,如果至少有一个没有,您将收到此错误(假设关系有效)
  • 不熟悉 eloquent 但仍然建议尝试更改 post 模型中的用户关系:代替 belongsTo - 尝试 hasOne
  • 与 dd($posts)?
  • User_id 大写.....应该是 user_id,修复你的数据库

标签: php laravel


【解决方案1】:

正确答案是return $this-&gt;belongsTo('App\User','User_id');

不是

 return $this->belongsTo('App\User','user_id');

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2018-01-01
    • 2018-04-05
    • 2017-11-05
    • 2017-12-27
    相关资源
    最近更新 更多