on a small project using laravel and javascript, I would like to implement a search functionality For this, I would like that once the search is submitted, the page content changes without reloading
So I have a first method in my controller, which renders the page view complete with my data In the page template, I included a file of partials, containing only my foreach loop and the associated html
Here is the controller method
public function __invoke(MyService $myService)
{
return view('posts.index', [
'posts' => $myService->getAll(),
]);
}
and my partials present in posts.index
@foreach($posts as $post)
<div class="">
<a href="{{ $post->url }}" class="text-xl font-bold inline-block">{{ $post->name }}</a>
<p class="my-4">
{{ str($post->data)->limit(150) }}
</p>
</div>
@endforeach
So, in my posts.index, I add this JS
var search = document.getElementById("search");
var by = document.getElementById("by");
var form = document.getElementById("form");
form.addEventListener("submit", function(evt) {
evt.preventDefault();
fetch('/search?search=' + search.value + '&by=' + by.value)
.then(response => response.json())
.then(data => {
var elem = document.querySelector('#result');
elem.innerHTML = JSON.stringify(data.html)
});
});
The #result element is where I'm including the partials
There is my search function
public function search(Request $request){
$by = $request->input('by');
switch ($by){
case 'name':
$service = new MyService();
$result = $service->getPostsForName($request->input('search');
$html = view('partials.list', ['posts' => compact('result')])->render();
return response()->json(compact('html'));
break;
}
}
The two methods of the controller return me an Array of Post (my model)
But when I run a search I always get the following error attempt to read property "url" on array in file
I can't understand why, could you help me please ?