Table of contents

Laravel 8 wherein() Query Example

In this post, I'm sharing how to use Laravel 8, and 9 whereIn() query from Eloquent and query builder. This method will able us to search many values in a single query using array values. I will provide an example for the Laravel whereIn() method so that it will be easier for you to understand and apply to your project.

 

The method whereIn() can be applied in the following versions of Laravel 6, 7, 8, and 9.

 

How does It work?

The below sample code using whereIn() method the first parameter is your field_name target and the second parameter will be an array of what you need to search or query.

wherein('field_name', $array_variable)

 

Now you have the basics of how it works. Let's try to do it with an example.

 

SQL Query Example:

SELECT *
  FROM posts
  WHERE id IN (1, 2, 3) 

 

 

WhereIn Query with Laravel 9 Query Builder

Wherein query example with IDs into an array.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $posts = DB::table('posts')
            ->whereIn('id', [1, 2, 3])
            ->get();

        print_r($posts);die;
    }
}

 

Wherein query example with post title into an array.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $posts = DB::table('posts')
            ->whereIn('title', ['post1', 'post2', 'post3'])
            ->get();

        print_r($posts);die;
    }
}

 

WhereIn Query with Laravel 9 Eloquent

Wherein query example with IDs into an array.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $posts = Post::whereIn('id', [21, 22, 23])->get();

        print_r($posts);die;
    }
}

 

Wherein query example with post title into an array.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {   
        $posts = Post::whereIn('title', ['post1', 'post2', 'post3'])->get();

        print_r($posts);die;
    }
}

 

That's it. I hope it helps.

 

Thank you for reading :)