Reputation: 733
I'm trying to make my own upvote/downvote system in laravel but i keep getting this error. however this error only appears when the user hasn't voted on one of the posts that is being shown as an example i'm showing all the posts to user and checking using getvote($post_id) function. the error only appears if the user hasn't voted on one of the posts however if he has voted on all of them then the error won't appear. here is my code to clarify more:
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;
}
}
view
@foreach ($posts as $post)
<div class="container">
<div class="posts">
<div class="card">
{{$post->getVote($post_id)}}
<img class="card-img-top" href="#" src="{{$post->image}}" alt="Card image cap">
<div class="card-block">
<h4 class="card-title">{{$post->title}}</h4>
<div class="vote">
<i class="fa fa-smile-o fa-fw green" aria-hidden="true" data-value="1" data-id="{{$post->post_id}}"></i>
<i class="fa fa-frown-o " aria-hidden="true" data-value="-1" data-id="{{$post->post_id}}"> {{$post->score}}</i>
</div>
<p class="card-text"><small class="text-muted" id="getDate" data-date="{{$post->created_at}}"><i class="fa fa-clock-o fa-fw" aria-hidden="true"></i></small>
by <a href="profile/{{$post->username}}"> {{$post->username}}</a></p>
</div>
</div>
</div>
</div>
@endforeach
Upvotes: 1
Views: 52
Reputation: 11192
Your error
Trying to get property of non object error
happens because your code is not verifying that
$uservote = PostVotes::where([
'post_id' => $post_id,
'username' => $username,
])->first();
returns an element. Remember that the Eloquent model returns null
if it doesn't match anything.
In that case $vote = $uservote->vote;
will try to get the vote
property of null
- and this will throw an exception
Instead, check that $uservote actually returns an element with a simple if statement:
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;
}
}
Upvotes: 1