Halnex Halnex - 2 months ago 10
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:
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() !!}

Answer

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.

Comments