简体   繁体   中英

Highlight search results in laravel 5.5

I am usiong laravel 5.5, I have a blade template in which I have a search, I want when the user types a keyword so the results comes with highlighted keywords. I have a code which works fine but when i try to loop it, shows me an error:

Invalid argument supplied for foreach()

my controller:

    $keyword = $request->name;

    $searchres = DB::table('brands')       
        ->select('*')
        ->where('name', 'LIKE', "%$keyword%")->get();

    $search = preg_replace("/($keyword)/i", "<b>$1</b>", $searchres);

    return view('frontend.ft_list', compact('search'));

blade template:

        @foreach($search as $result)
            <div class="card" style="border-radius: 1rem;width: 100%">
                <h5 class="card-header" style="text-align: center; font-weight: bold">{{$result->name}}</h5>
                <div class="card-body">
                    <h5 class="card-title">{{$result->published}}</h5>
                    <p class="card-text" style="text-align: center;font-weight: bold">{{$result->user_id}}</p>
                </div>
            </div>
            <br>
            <br>
        @endforeach

I would really appreciate if someone could help me with it. Thanks in advance!!

Ok i have an idea and i hope that it going to help you

$keyword = $request->name;

$searchres = DB::table('brands')       
    ->select('*')
    ->where('name', 'LIKE', "%$keyword%")
    ->get()
    ->map(function ($row) use ($keyword) {
        $row->name = preg_replace('/(' . $keyword . ')/i', "<b>$1</b>", $row->name);
        return $row;
    });

return view('frontend.ft_list', compact('searchres'));

and in the blade use

{!! $yourvariable !!}

and don't use

{{ $yourvariable }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM