Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel试图获取非对象错误的属性_Php_Laravel - Fatal编程技术网

Php Laravel试图获取非对象错误的属性

Php Laravel试图获取非对象错误的属性,php,laravel,Php,Laravel,我试图在拉雷维尔建立我自己的向上投票/向下投票系统,但我一直得到这个错误但是,此错误仅在用户未对正在显示的帖子之一进行投票时出现例如,我向用户显示所有帖子,并使用getvote($post_id)功能进行检查。只有当用户没有对其中一篇文章进行投票时,错误才会出现。但是,如果用户对所有文章都进行了投票,则不会出现错误。以下是我的代码,以进一步说明: public function getVote($post_id) { $username = Session::get('username')

我试图在拉雷维尔建立我自己的向上投票/向下投票系统,但我一直得到这个错误但是,此错误仅在用户未对正在显示的帖子之一进行投票时出现例如,我向用户显示所有帖子,并使用getvote($post_id)功能进行检查。只有当用户没有对其中一篇文章进行投票时,错误才会出现。但是,如果用户对所有文章都进行了投票,则不会出现错误。以下是我的代码,以进一步说明:

public function getVote($post_id) 
{
  $username = Session::get('username');
  if(isset($username)) {
  $uservote = PostVotes::where([
        'post_id' => $post_id,
        'username' => $username,
    ])
    ->first();
    $vote = $uservote->vote;
   if(!$vote)
   {
     return;
   }
   return $vote;  
  } else {
    return null;
  }
}
看法

@foreach($posts as$post)
{{$post->getVote($post_id)}
image}“alt=”卡片图像帽“>
{{$post->title}
{{$post->score}

@endforeach
您的错误

试图获取非对象错误的属性

发生这种情况的原因是您的代码没有验证这一点

$uservote = PostVotes::where([
      'post_id' => $post_id,
      'username' => $username,
  ])->first();
返回一个元素。请记住,如果与任何内容不匹配,雄辩的模型将返回
null

在这种情况下,
$vote=$uservote->vote;
将尝试获取
vote
属性的
null
,这将引发异常

相反,检查$uservote是否实际返回一个带有简单if语句的元素:

public function getVote($post_id) 
{
  $username = Session::get('username');
  if(isset($username)) {
  $uservote = PostVotes::where([
        'post_id' => $post_id,
        'username' => $username,
    ])
    ->first();

    if ($uservote) {
        $vote = $uservote->vote;
    }

   if(!$uservote)
   {
     return;
   }
   return $vote;  
  } else {
    return null;
  }
}

@flex_u这是因为$uservote不返回结果。我稍微调整了代码以处理此问题,将
if(!$vote)
替换为
if(!$uservote)
谢谢你这么做。顺便说一句,我只是想问一下,这是处理投票的好方法还是我应该使用关系?@flex\u在没有看到整个应用程序结构的情况下,很难回答这个问题,但这样做没有错。
public function getVote($post_id) 
{
  $username = Session::get('username');
  if(isset($username)) {
  $uservote = PostVotes::where([
        'post_id' => $post_id,
        'username' => $username,
    ])
    ->first();

    if ($uservote) {
        $vote = $uservote->vote;
    }

   if(!$uservote)
   {
     return;
   }
   return $vote;  
  } else {
    return null;
  }
}