Highlight Keywords in Search Results with Laravel

Highlight Keywords in Search Results with Laravel 6.0, Laravel 5.8, Laravel 5.7, Highlight search results in laravel 5.6, laravel 5.5, laravel 5.4, laravel 5.3, laravel 5.2, Highlight search results in laravel, Highlighting Keywords in search results with Laravel

Overview

Step 1:- Create Blade File (resources/views/highlightkeywords.blade.php).
Step 2:- Create URL into Routes File For Highlight Keywords (routes/web.php).
Step 3:- Create Controller File (app/Http/Controllers/HighlightController.php).

 

Step 1:- Create Blade File (resources/views/highlightkeywords.blade.php).

 

<!DOCTYPE html>
<html>
<head>
<title>Highlight Keywords in Search Results with Laravel</title>
</head>
<body>
<h1>Highlight Keywords in Search Results with Laravel</h1>
<form>
<div class="input-group">
<input type="text" name="searchnews" id="searchnews" class="form-control ui-autocomplete-input" placeholder="Search News...." autocomplete="off">
<div class="input-group-append"><button><i class="fas fa-search"></i></button></div>
</div>
<ul id="news_id">
//show results here
</ul>
</form>
<script src=https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js></script>
<script> $(document).ready(function() { 
$("#searchnews").autocomplete({ source: function(e, t) { 
var t = $("input[name='_token']").val(); 
$.ajax({ 
url: "/search_keywords", 
method: "GET", 
data: { term: e.term, t:t}, 
dataType: "text", 
success: function(e) { 
$("#news_id").html(e); 
} 
}); 
} 
}); 
});
</script>
</body>
</html>

 

Step 2:- Create URL into Routes File For Highlight Keywords (routes/web.php).

 

<?php
Route::get('highlightkeywords', function () {
return view('highlightkeywords');
});
Route::get('search_keywords', 'HighlightController@search_keywords');

 

Step 3:- Create Controller File (app/Http/Controllers/HighlightController.php).

 

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use DB;
use Redirect;
use View;
class HighlightController extends Controller
{
public function search_keywords(Request $req)
{
$title = $req->term; 
$data = DB::table('blog')->where('title', 'like', '%' . $title . '%')->take(10)->get();
foreach ($data as $key => $value) {
echo '<li><a href='.url('news/'.$data[$key]->category.'/'.$data[$key]->slug).'>'.str_replace(strtolower($t),"<b>".strtolower($t)."</b>", strtolower($data[$key]->title)).'</a></li>';
}
}
}