Laravel-5 'LIKE' equivalent (Eloquent)
I'm using the below code to pull some results from the database with Laravel 5.
BookingDates::where('email', Input::get('email'))->orWhere('name', 'like', Input::get('name'))->get()
However, the orWhereLike doesn't seem to be matching any results. What does that code produce in terms of MySQL statements?
I'm trying to achieve something like the following:
select * from booking_dates where email='[email protected]' or name like '%John%'
If you want to see what is run in the database use dd(DB::getQueryLog())
to see what queries were run.
Try this
BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
I have scopes for this, hope it help somebody. https://laravel.com/docs/master/eloquent#local-scopes
public function scopeWhereLike($query, $column, $value)
{
return $query->where($column, 'like', '%'.$value.'%');
}
public function scopeOrWhereLike($query, $column, $value)
{
return $query->orWhere($column, 'like', '%'.$value.'%');
}
Usage:
$result = BookingDates::whereLike('email', $email)->orWhereLike('name', $name)->get();
$data = DB::table('borrowers')
->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
->select('borrowers.*', 'loans.*')
->where('loan_officers', 'like', '%' . $officerId . '%')
->where('loans.maturity_date', '<', date("Y-m-d"))
->get();
I think this is better, following the good practices of passing parameters to the query:
BookingDates::whereRaw('email = ? or name like ?', [$request->email,"%{$request->name}%"])->get();
You can see it in the documentation, Laravel 5.5.
You can also use the Laravel scout and make it easier with search. Here is the documentation.