I’m making a functionality to search for records
controller
public function search(Request $request)
{
$textSearch = $request->get('blog-search');
$articleSearch = Article::where('title', 'LIKE', '%'.$textSearch.'%')->get();
return view('blog.search-list', compact('articleSearch'));
}
route
Route::get('/search', 'App\Http\Controllers\BlogController@search');
search.blade.php
<div class="blog-search">
<form id="search" action="/blog/" method="get" role="search">
<input type="text" id="blog-search" name="blog-search" autocomplete="off">
<div class="blog-search-result" id="blog-search-result"></div>
</form>
</div>
search-list.blade.php
<?php if ($articleSearch) { ?>
<div class="list block-shadow">
<?php foreach ($articleSearch as $article) { ?>
<a href="<?= $article->getUrl() ?>"><?= $article->title ?></a>
<?php } ?>
</div>
<?php } ?>
js
$(document).on('keyup', '[name="blog-search"]', function () {
let data = $(this).closest('form').serialize();
let searchResult = $('#blog-search-result');
searchResult.html('');
if ($(this).val().length < 2) {
return;
}
$.ajax({
url: '/search',
data: data,
method: 'get',
success: function (result) {
searchResult.html(result.html);
}
});
});
As a result, the search works and in the network I get this piece of code
But the problem is that this piece of code should appear in this block <div class="blog-search-result" id="blog-search-result"></div>
And I still can’t figure out where to do it
>Solution :
You’ve got the right idea, but you can’t return a view() like that if you’re expecting to inject it into the DOM as HTML. Use this approach instead:
public function search(Request $request) {
$textSearch = $request->get('blog-search');
$articleSearch = Article::where('title', 'LIKE', '%'.$textSearch.'%')->get();
$html = view('blog.search-list', compact('articleSearch'))->render();
return response()->json(['html' => $html], 200);
}
The render() method converts the view to a string, which you then pass back as JSON via response()->json(). Your AJAX handler is correct; searchResult.html(result.html);
Sidenote, if you’re using .blade.php, you don’t need raw PHP:
@if($articleSearch)
<div class="list block-shadow">
@foreach($articleSearch as $article)
<a href="{{ $article->getUrl() }}"><{{ $article->title }}></a>
@endforeach
</div>
@endif
@if() can replace your <?php if (...) { ?>, and @foreach() can replace <?php foreach(...) } ?> (along with @endif and @endforeach)
