[英]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)
in_array()期望参数2是数组,给定对象(查看: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()
我试过使用
lists()
但是我得到了这个错误而不是Missing argument 1 for Illuminate\\Database\\Eloquent\\Builder::lists()
Using lists('post_id')
returns the same error in the title. 使用
lists('post_id')
在标题中返回相同的错误。
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: 只需将
toArray()
附加到您的查询,如下所示,因为'toArray()'将集合转换为普通的PHP数组:
$votes = Auth::user()->votes()->get()->toArray();
Hope this help. 希望这有帮助。
我认为采摘会解决你的问题。
$voteIds = Auth::user()->votes()->get()->pluck('id')->toArray();
You can convert the collection to an array like other suggested using toArray()
method. 您可以使用
toArray()
方法将集合转换为其他建议的数组。 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. 以上仅在
$votes
是ID集合时有效。 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. 因为
$votes
是Vote
对象的集合,您只想在post_id
列/属性中搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.