I am trying to pass an array with the logged-in user's votes on the posts from the controller to the view but I keep getting this error
in_array() expects parameter 2 to be array, object given (View: C:\xampp\htdocs\laravel-5\resources\views\subreddit\show.blade.php)
I have tried to use lists()
but I got this error instead Missing argument 1 for Illuminate\Database\Eloquent\Builder::lists()
Using lists('post_id')
returns the same error in the title.
Controller
public function show(Subreddit $subreddit)
{
$posts = Subreddit::findOrFail($subreddit->id)->posts()->get();
$votes = Auth::user()->votes()->get(); //I have also tried lists()
return view('subreddit/show')
->with('subreddit', $subreddit)
->with('posts', $posts)
->with('votes', $votes);
}
View
@foreach($posts as $post)
@if ($voted = in_array($post->id, $votes))
{!! Form::open(['url' => 'votes', 'class' => 'votes']) !!}
@endif
<div class="upvote topic" data-post="{{ $post->id }}">
<a class="upvote vote {{ $voted ? 'voted-on' : '' }}" data-value="1"></a>
<span class="count">0</span>
<a class="downvote vote {{ $voted ? 'downvoted-on' : '' }}" data-value="-1"></a>
</div>
{!! Form::close() !!}
You need to convert your collection to array. Just append toArray()
to your query like below, as 'toArray()' converts the collection into a plain PHP array:
$votes = Auth::user()->votes()->get()->toArray();
Hope this help.
You can convert the collection to an array like other suggested using toArray()
method. But i'd rather change
in_array($post->id, $votes)
to
$votes->contains($post->id)
The above only works if $votes
is a collection of IDs. Eg. when you use
$votes = Auth::user()->votes()->pluck('post_id');
However, with your current controller code you would need to use
$votes->contains('post_id', $post->id);
since $votes
is a collection of Vote
objects, and you only want to search in the post_id
column/attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With