Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4/5 search form like

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.

like image 627
erm_durr Avatar asked Aug 16 '13 23:08

erm_durr


3 Answers

Hmmm, yes, just set like as your comparison operator, and send the string with %'s. Something like this:

Player::where('name', 'LIKE', "%$name%")->get();
like image 87
rmobis Avatar answered Nov 04 '22 21:11

rmobis


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();
like image 23
Yaroslav Avatar answered Nov 04 '22 20:11

Yaroslav


With quote of string:

$value = DB::connection()->getPdo()->quote('%' . strtolower($value) . '%');
$query->whereRaw('LOWER(your_table.your_column) LIKE ' . $value);
like image 1
Nick Avatar answered Nov 04 '22 19:11

Nick