Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
Laravel - JS : search function without reloading page, return html

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 ?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda