blueink
blueink

Reputation: 69

Laravel ambiguous string search

I have a problem about search. I can make basic search. I would like to make more advanced search Like search.

For example. database's table has "AAA" string at 'pn' colum. I would like to show the record when I type "aaa" search text area.

I made this below but it didn't work. Could somebody tell me what is the problem please?

public function show(Request $request)
{
    if (isset($request->pn)) {
        $param = ['pn' => $request->pn];
        $item = DB::select('select * from sts where pn collate utf8_unicode_ci like '%'.$pn.'%'', $param);      
    } else {
        $items = DB::select('select * from sts');
    }
    return view('pn.searchshow', ['items' => $items]);
}

Upvotes: 1

Views: 69

Answers (2)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

public function show(Request $request)
{
    $query = \DB::table('sts');
    if (isset($request->pn)) {
        $query->where(DB::raw('`pn` callate utf8_unicode_ci'), 'like', '"%' . $request->pn . '%"');
    }

    $items = $query->get();
    return view('pn.searchshow', ['items' => $items]);
}

Upvotes: 0

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

The binding has to include the % wildcards:

$param = ['pn' => '%'.$request->pn.'%'];
$item = DB::select('select * from sts where pn collate utf8_unicode_ci like :pn', $param);

Upvotes: 2

Related Questions