Search code examples
phplaravel-5eloquentwhere-inlaravel-query-builder

Get any of the item from the Array with whereIn in Laravel 5.3


I'm using laravel 5.3 and trying to build a query with multiple where and wherein function. Here is my code:

$posts_id = "1,3,4";  //from my query
$results = Post::select('*');   
$results->whereIn('posts_id', [$posts_id]);
$resutls->get();

There is 1 post which have an id of 4 in my database, but my query doesn't returning anything. Though there is 4 in my post ids $posts_id = "1,3,4";.

Need help, to get posts from any of the id, which I've included in my $posts_id variable.

Thanks in Advance!


Solution

  • You need to pass an array to whereIn() method:

    $results = Post::whereIn('posts_id', explode(',' $posts_id))->get();
    

    Note that you don't need to call each method in a separate line. You can chain them. Also, the select('*') is not required.

    You can create your array in any way you want, no need to use explode().

    $ids = [1, 2, 3];
    $results = Post::whereIn('posts_id', $ids)->get();
    

    It may be good to check if the array isn't empty before making that query.