Halnex
Halnex

Reputation: 4526

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() !!}

Upvotes: 11

Views: 47504

Answers (3)

Paul Spiegel
Paul Spiegel

Reputation: 31802

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)

Update

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.

Upvotes: 10

Suren
Suren

Reputation: 76

I think pluck will solve your problem.

$voteIds = Auth::user()->votes()->get()->pluck('id')->toArray();

Upvotes: 5

mdamia
mdamia

Reputation: 4557

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.

Upvotes: 36

Related Questions