Adding an AJAX Live Search Function - Part 2 - Adding the Controller Search Function

Next we will add a route member.search and a matching controller function. This function will retrieve the character/characters typed by the user into the search box on the form. Using this value it will search the existing Members using Eloquent and trying to match what was typed with a either a member's firstname or surname. Don't add this next block just yet. It's presented here for explanation purposes.

$members=\App\Models\member::where('surname','LIKE','%'.$searchvalue.'%')->orWhere('firstname','LIKE','%'.$searchvalue.'%')->get();

The flexibility of searching by either firstname or surname is achieved by chaining together arrow functions. Method chaining is a nice feature of PHP that allows us to call multiple functions of a class in a single instruction.

The Eloquent "where" function in this case will translate to a SQL where clause while the "LIKE" is equivalent to a SQL "LIKE" expression which will match two strings that are similar even if they are not identical. The LIKE operator together with method chaining which allows us to search two different columns provides a very effective and flexible search feature.

To try this out add the following function to \App\Controllers\memberController.php

    public function search(Request $request)
    {
        $output="";
        $searchvalue = $request->search;
        if($request->ajax()) {
            $members=\App\Models\member::where('surname','LIKE','%'.$searchvalue.'%')->orWhere('firstname','LIKE','%'.$searchvalue.'%')->get();
            if($members->count()>0) {
                
                foreach ($members as $member) {
                    $output='<tr>';
                    $output=$output . '<td>'.$member->id.'</td>';
                    $output=$output . '<td>'.$member->firstname.'</td>';
                    $output=$output . '<td>'.$member->surname.'</td>';
                    $output=$output . '<td>'.$member->membertype.'</td>';
                    $output=$output . '</tr>'; 
                }
                return Response($output);
            }
            return Response("No Match");
        }
        else {
            return Response("error");
        }
    }    

For this to work we need to add the following matching route to routes\web.php

Route::get('member/search','App\Http\Controllers\MemberController@search')->name('member.search');