Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stefverniers's avatar

Laravel: Ajax live search returns error 405 (METHOD NOT ALLOWED)

I'm following a tutorial to implement live search feature in my laravel project using ajax.

I'm following the tutorial and understand every stap he takes but I recieve an error 405 (Method not allowed). Can anyone see what I'm doing wrong?

Here's my code:

My view:

<body class="relative min-h-screen">
    @include('partials.header')
    <main class="md:w-3/5  m-auto pb-20 space-y-10">
        <div class="p-2 mt-4 flex justify-center items-center">
            <p class="w-10/12">Welkom Admin. Op deze pagina kan je al onze gebruikers terugvinden en heb je beheer over hun geboortelijst.
            </p>
        </div>
        <div class="bg-mid p-4 mb-8 flex flex-row justify-between items-center ">
            <h3 class=""><strong>Gebruikers</strong></h3>
        </div>
        <input type="search" name="search" id="search" class="border-2 rounded-lg p-2">
        <div class="w-full bg-mid p-2" id="Table">
        </div>
    </main>
    @include('partials.footer')

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha512-+NqPlbbtM1QqiK8ZAo4Yrj2c4lNQoGv8P79DPtKzj++l5jnN39rHA/xsqn8zE9l0uSoxaCdrOgFs6yjyfbBxSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha512-ldc1sPu1FZ8smgkgp+HwnYyVb1eRn2wEmKrDg1JqPEb02+Ei4kNzDIQ0Uwh0AJVLQFjJoWwG+764x70zy5Tv4A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    {{-- Script voor live searching --}}
    <script>
        $(document).ready(function(){
            $('#search').on('keyup', function(){
                const query = $(this).val();
                $.ajax({
                    url:"search",
                    type: "GET",
                    data:{'search': query},
                    success: function(data){
                        $('$Table').html(data);
                    }
                });
            });
        });
    </script>

</body>

My routes:

Route::get('/admin/home', [AdminController::class, 'adminHome'])
    ->name('adminhome');

Route::get('/admin/home/search', [AdminController::class, 'search'])
    ->name('search');

My Controller:

public function search(Request $request) 
{

    $users = User::where('role', '=', 'user')->get();

    if($request->ajax()) {
        $data = $users->where('id', 'like', '%'.$request->match.'%')
            ->orwhere('name', 'like', '%'.$request->match. '%')
            ->orwhere('email', 'like', '%'.$request->match. '%')->get();

        $output = '';
    if (count($data) > 0) {
        
        $output = `
        <table>
        <thead>
        <tr>
            <th scope="col">Id</th>
            <th scope="col">Naam</th>
            <th scope="col">E-mail</th>
        </tr>
        </thead>
        <tbody>`;
            foreach ($data as $row) {
                $output .=`
                <tr>
                    <th scope="row">`.$row->id.`</th>
                    <td>`.$row->name.`</td>
                    <td>`.$row->email.`</td>
                </tr>
                `;
            }

        $output .= `
        </tbody>
        </table>`;   
        }
    } else {
        $output = 'Geen gebruikers voldoen aan uw zoekcriteria..';
    }
}
0 likes
36 replies
Sinnbeck's avatar

You set the url to search url:"search",

Yet your routes are different. Try this

url: "/admin/home/search", 
Sinnbeck's avatar

@stefverniers so your ajax calls the exact same url as you manually do? Check the network tab in dev tools (f12)

Sinnbeck's avatar

@stefverniers I assumed you wanted this url? /admin/home/search

Check the url you want in the browser compare

stefverniers's avatar

@Sinnbeck I would. I tried out of curiosity to change the url in my ajax properties to 'admin/home' and when I typed in my search field, My homepage rendered into the div where the result should come with a positive feedback in the network tab

Sinnbeck's avatar

@stefverniers remember the leading slash.

These are not the same (second is correct)

admin/home
/admin/home
Sinnbeck's avatar

@stefverniers ok let's try again then. Use the correct url. What happens? Sounds like it's working correctly with the wrong url

Sinnbeck's avatar

Also let me suggest returning a view instead of manually writing html in the controller

stefverniers's avatar

@Sinnbeck When I use the right URL. the moment I start typing inside the search field, for every keyup, it returns an error 500

stefverniers's avatar

The error that I get contains an email so I can't post that because it's my first day on laracasts..

stefverniers's avatar

@Sinnbeck If I do that, there is nothing much left to write. except the error just says internal server error..

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@stefverniers debug by just returning a simple string and if that works, move that html to a view file

click's avatar

Note that you never return anything in your public function search(). You only save something in $output but you never return it.

Also you use the backtick after $output .= instead of the '.

Currently your logic in your controller is this:

$users = get ALL users from the database

if ($this_is_an_ajax_call) { 
   $data = $data /* filter on the collection (not a db query filter) */
   if (we_have_results_in_data) {
        // build html table 
   }
    
} else {
  // not an ajax call
}

You are now 100% sure you end up at the correct route? Can you add a dd($request->all()) to the top of your search() method and confirm you are on the correct route?

stefverniers's avatar

@click With a dd($request->all()), nothing happens Keep in mind I'm still on my /admin/home

stefverniers's avatar

@click The view I've posted is the /admin/home/. That is returned by the adminHome method, which is the first route

click's avatar

@stefverniers I'm a bit lost on where you are now. It seems like multiple problems are going on.

  1. Your problem is (still) in the ajax call?
  2. Did you make the changes as sinnbeck suggested?
  3. Can you confirm you are now making the ajax calls to the correct route: /admin/home/search ?
stefverniers's avatar

@click I can't confirm if I'm making the right call to the route.. Any tips to start over?

stefverniers's avatar

I got a breakthrough. When I'm typing something, my console gives me a response which I've written inside the ajax succes function. But the problem now is, not a table with data, but my entire homepage got rendered inside that div where my table should be rendered..

Sinnbeck's avatar

@stefverniers as you are returning html, use a view make it. So get that working first and just call the route in a browser tab while developing :)

Sinnbeck's avatar

@stefverniers I think you are getting the wrong url which probably work as you return a view, just like I suggest for the search route

stefverniers's avatar

@Sinnbeck Any chance you can tell me how to construct the view with the data I've written inside my controller? I have no clue how to start..

stefverniers's avatar

Another breakthrough! Everytime I write a new character in my searchfield, a new console log is written But still no data to see..

stefverniers's avatar

2 more questions.

  1. What if I want to display the whole list of users I already have, and then remove the list and only show the ones that are getting validated by the search bar?
  2. Every user has a role. How can I exclude specific roles like the admin accounts?

Please or to participate in this conversation.