【问题标题】:Laravel 4 Property of non-object on NginxLaravel 4 Nginx 上非对象的属性
【发布时间】:2015-12-23 12:17:39
【问题描述】:

我在运行 MAMP 服务器(所以 apache)的笔记本电脑上运行了以下代码。在我的系统上它工作得非常好,然而,当我将它推送到我的服务器时,它开始抛出“试图获取非对象错误的属性。数据库和迁移都是最新的,并反映我的笔记本电脑上的设置。我想知道为什么这会发生在我的服务器上而不是我的笔记本电脑上。它似乎也是随机发生的,这让我认为这可能是缓存问题?

foreach($posts as $post){
    $user = User::where("id","=",$post->posted_by)->first();
    $response['posts'][] = [
        'id' => $post->id,
        'username' => $user->username, //causes problem
        'firstname' => $user->name, //causes problem
        'lastname' => $user->lastname, // causes problem
        'images' => $post->getPostImages(),
        'title' => $post->title,
        'content' => $post->content,
        'price' => $post->price,
        'category' => Category::find($post->category_id)->title //causes problem
     ];
}

【问题讨论】:

  • 帖子的posted_by 属性是外键吗?您确定所有posted_by 用户都存在吗?
  • 你没有任何 $user !所以 dd($user) 来检查一下!
  • @watcher 虽然你的回答不是我的确切问题,但这是一般的想法。我发现类别没有正确发布并且缺少数据库 ID。感谢您的评论
  • 我建议始终检查事物是否存在,所以只需检查 if($post)。这是一个很好的工作习惯。

标签: php laravel nginx laravel-4


【解决方案1】:

这是因为找不到类别对象

你应该把你的代码改成这个

foreach($posts as $post){
    $user = User::where("id","=",$post->posted_by)->first();

    //check if category id is set
    if(!$post->category_id)
        abort(500,'category_id is not set with Post: #'.$post->id);

    //get the category
    $category = Category::find($post->category_id);

    //check if it found a category
    if(!is_object($category)){
        abort(500,'could not find Category: #'.$post->category_id);
    }

    $response['posts'][] = [
        'id' => $post->id,
        'username' => $user->username, //causes problem
        'firstname' => $user->name, //causes problem
        'lastname' => $user->lastname, // causes problem
        'images' => $post->getPostImages(),
        'title' => $post->title,
        'content' => $post->content,
        'price' => $post->price,
        'category' => $category->title //causes problem
     ];
}

此更改应该可以帮助您找出缺少的内容:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-05
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2017-10-07
    • 2018-06-15
    相关资源
    最近更新 更多