Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

421
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda