Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

420
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!