How to add ‘like’ and ‘equal’ in same query in Laravel

We can search for results in an application using different keywords like ‘Like’ and ‘Equal’. Both hold a different criteria. However, we can use ‘like’ and ‘equal’ in same query at the same time.

We use the LIKE query in a where clause to look for a specific pattern in column records. As shown below, it is used with the % and _ SQL wildcards in Laravel to get similar results.

            ->where('name', 'like', '%' . 'Alice')

You can use the ‘equal’ or ‘=’ in Laravel queries along with the where clause as show below.

            ->where('name', '=', 'Alice')

This searches the customers table for the user with the name equal to ‘Alice’

The difference between the above two code snippets is that with ‘like’ it prints names with first name Alice and also anything added after Alice, as it hold no closure wildcard. The equals condition just returns name with ‘Alice’.

Let us demonstrate an example to where we can use ‘equal’ and ‘like’ both in the same Laravel database query.

$data = DB::table('customers')
        ->join('loans', '', '=', 'loans.customers_id')
        ->select('customers.*', 'loans.*')   
        ->where('loan_borrowers', 'like', '%' . $customer_name . '%')

The above query joins the customers and loans tables to check where the customer id in both tables is equal. It then selects those records and puts a where condition to print those results where the loan_borrowers names are exactly the same as the customer names, using the like keyword.

Leave a Comment