tntsearch icon indicating copy to clipboard operation
tntsearch copied to clipboard

Highlighting with Laravel 5.5

Open TheBigK opened this issue 7 years ago • 2 comments

I'm super impressed with the results I'm getting with TnTSearch integration with Laravel. Would really appreciate if someone could show me how to use highlighting feature within Laravel. I've this

$threads = Thread::search($request->s)->paginate(5);

this does produce desired results. But how do I add highlighting to output?

TheBigK avatar Feb 06 '18 14:02 TheBigK

Here's how I did it. You can see the avilable highlight options by inspecting the Highlighter class.

use TeamTNT\TNTSearch\TNTSearch;

class ThreadController extends Controller {

    public function search(TNTSearch $tnt, Request $request)
    {
        Thread::search($request->s)->paginate(5)->map(function($thread) use ($tnt, $request){
            $thread->title = $tnt->highlight($thread->title, $request->s, 'b', ['wholeWord' => false]);
            return $thread;
        });
    }

}

markgp avatar Mar 08 '18 21:03 markgp

@markgp My pagination fails when doing that. For example, I cannot use $thread->links(). Removing the map() part makes it work again.

Edit: Using this:

$threads = Thread::search($request->s)->paginate(5); // Stop chaining here
$threads->map(function($thread) use ($tnt, $request) {
    $thread->title = $tnt->highlight($thread->title, $request->s, 'b', ['wholeWord' => false]);
    return $thread;
});

Rather than what you suggested:

$threads = Thread::search($request->s)->paginate(5)->map(function($thread) use ($tnt, $request) {
    $thread->title = $tnt->highlight($thread->title, $request->s, 'b', ['wholeWord' => false]);
    return $thread;
});

Seems to work :+1:

Also, most of the time, you want to match the whole word, so set ['wholeWord' => true].

Important: Don't forget to protect against XSS attacks by adding the e() function:

$threads = Thread::search($request->s)->paginate(5);
$threads->map(function($thread) use ($tnt, $request) {
    $thread->title = $tnt->highlight(e($thread->title), $request->s, 'b', ['wholeWord' => true]);
    return $thread;
});

pedzed avatar Nov 04 '18 17:11 pedzed