Halnex Halnex - 1 year ago 169
PHP Question

Laravel 5: in_array() expects parameter 2 to be array, object given

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:

I have tried to use
but I got this error instead
Missing argument 1 for Illuminate\Database\Eloquent\Builder::lists()

returns the same error in the title.


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);


@foreach($posts as $post)
@if ($voted = in_array($post->id, $votes))
{!! Form::open(['url' => 'votes', 'class' => 'votes']) !!}
<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>
{!! Form::close() !!}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download