Home  >  Article  >  Backend Development  >  How to Achieve Partial Matching using `orWhereLike` in Laravel-5 Eloquent?

How to Achieve Partial Matching using `orWhereLike` in Laravel-5 Eloquent?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 10:59:02613browse

How to Achieve Partial Matching using `orWhereLike` in Laravel-5 Eloquent?

Using 'LIKE' Equivalent with Laravel-5's Eloquent

When attempting to retrieve data from a database using Laravel-5, users may encounter difficulties using the orWhereLike method to match results. To understand this issue, let's explore the MySQL statement equivalent to the provided code:

BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', Input::get('name'))
->get()

This code translates to the following MySQL statement:

<code class="sql">select * from booking_dates where email='[email protected]' or name like 'John'</code>

However, the expected MySQL statement should look like:

<code class="sql">select * from booking_dates where email='[email protected]' or name like '%John%'</code>

To resolve this discrepancy and achieve the desired matching, use the following code:

<code class="php">BookingDates::where('email', Input::get('email'))
    ->orWhere('name', 'like', '%' . Input::get('name') . '%')
    ->get();</code>

This modified code ensures that the percentage sign (%) is added to the beginning and end of the input name, allowing for partial matching.

Additionally, remember that if you wish to examine the queries generated by Laravel, you can use the following command:

<code class="php">dd(DB::getQueryLog())</code>

The above is the detailed content of How to Achieve Partial Matching using `orWhereLike` in Laravel-5 Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn