Laravel 4/5 search form like
56,292
Solution 1
Hmmm, yes, just set like
as your comparison operator, and send the string with %
's. Something like this:
Player::where('name', 'LIKE', "%$name%")->get();
Solution 2
If you need to frequently use LIKE, you can simplify the problem a bit. A custom method like () can be created in the model that inherits the Eloquent:
public function scopeLike($query, $field, $value){
return $query->where($field, 'LIKE', "%$value%");
}
So then you can use this method in such way:
User::like('name', 'Tomas')->get();
Solution 3
With quote of string:
$value = DB::connection()->getPdo()->quote('%' . strtolower($value) . '%');
$query->whereRaw('LOWER(your_table.your_column) LIKE ' . $value);
Author by
erm_durr
Updated on August 14, 2020Comments
-
erm_durr over 3 years
I have a search form and functions, all done. Just to ask, is it possible to do it in Eloquent a query like this:
SELECT * FROM players WHERE name LIKE '%".$name."%'
To display some possible matching names. My current controller function:
public function search() { $name = Input::get('character'); $searchResult = Player::where('name', '=', $name)->paginate(1); return View::make('search.search') ->with('name', $name) ->with('searchResult', $searchResult); }
And my view:
<form id="custom-search-form" class="form-search form-horizontal pull-right" action="{{ URL::action('CharactersController@search') }}" method="get"> <div class="input-append spancustom"> <input type="text" class="search-query" name="character" placeholder="Character/guild name"> <button type="submit" class="btn"><i class="icon-search"></i></button> </div> </form>
Thanks in advance.
-
erm_durr over 10 yearsThanks, never really made things with LIKE queries. How could I get the matching results? I already have a search form setup, but don't know how to view the matching results? Could you help me a bit? paste.laravel.com/K9O
-
rmobis over 10 yearsYou can take a look at how to display paginated results on Laravel docs. Also, I'd recommend you indent your view code, it's barely readable.
-
Andrew Koper about 10 yearsThis is helping me with my jquery autocomplete case, too.
-
Ezekiel Victor over 8 yearsThis may produce unexpected results when user has inputted "%" into $name FYI.
-
Josh Petitt over 7 yearswhere would I put the function 'scopeLike'? Which file?
-
Den Kison about 7 years@JoshPetitt, you need to put this method inside your model and framework will see it automatically. (here is docs - laravel.com/docs/5.4/eloquent#query-scopes see local scopes)