skip to Main Content

I’m making a searchbar for my website, I wanna filter users for username.
My function in controller look like this:

  function search_users(Request $request) {
        if ($request->search) {
            $searchUsers = User::where('username', 'LIKE', '%'. $request->search. '%')->get();
            $data = [
                "users" => $searchUsers
            ];
            //return response()->json($searchUsers);
          return view('dashboard.home', $data);
        }else {
            return response()->json("no_results");
          //  return view('dashboard.home');
        }
    }
    <form action="{{route('search')}}" method="get">
                <input type="search" name="username" id="" placeholder="Cerca" class="searchbar">
                <button type="submit">Search</button>
            </form>

If I try to make a search I receive no_results response also if I have this username stored into db, probably I wrong to set something inside my blade file

2

Answers


  1. Inside your form you named the input as

    name="username"
    

    inside your controller you have to use the same name

    if ($request->username)
    
    Login or Signup to reply.
  2. Replace $request->search by $request->username, because the name of your input is username and you used the type of the input

     function search_users(Request $request) {
        if (isset($request->username)) {
            $users = User::where('username', 'LIKE', '%'. $request->username.'%')->get();
    
        }else{
           $users = null;
        }
      return view('dashboard.home', $users);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search