Reputation: 340
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!!
Upvotes: 3
Views: 1641
Reputation: 741
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 }}
Upvotes: 2