2
votes

I'm trying to build a search system in my small laravel project but considering that I'm still a beginner I can't figure how this should work..

Basically, I have a controller which returns an index page with all the users. In the index page I have multiple select tags where you can choose an option and filter the users.

Here's my index method:

public function index(){

  $users = User::all();
  $service = Service::all();

  return view('browse.index', compact('users','service'));
}

Now, the thing is, I have a relationship built between users and services. So, each user hasMany services. With that in mind, when I'm building the search function I want to be able to access the user service. Something like this:

  $category = $request->input('category');

  foreach ($users as $user) {
    $serviceFound = $user->service->where('category', 'LIKE', '%' . $category . '%');
  }

Of course this doesn't work because considering that I have a get route for my index, I don't know how to set up the form so I can use the $request.. I hope this is clear...Maybe you guys can help me with setting up the form/route and clear my mind on how should I do this...

2
Perhaps, if you want to get the best and easiest filtering options in your view try datatables.Anna Jeanine

2 Answers

3
votes

Build a simple form using GET as well. Simple Example

<form action="" method="GET">
    <input type="text" name="category" required/>
    <button type="submit">Submit</button>
</form>

In your controller you do

public function index(Request $request){
    $category = $request->input('category');

    //now get all user and services in one go without looping using eager loading
    //In your foreach() loop, if you have 1000 users you will make 1000 queries

    $users = User::with('services', function($query) use ($category) {
         $query->where('category', 'LIKE', '%' . $category . '%');
    })->get();

    return view('browse.index', compact('users'));
}

Eager loading will work only if you have your relationships setup properly.
Keep your route unchanged the way it is now.

0
votes

In your controller:

public function index(\Request $request)
{
    return $request::all();
}

In your routes:

Route::get('searchtest', 'SearchController@index');

Example url:

http://localhost:8000/searchtest?search=search_string&category=socks

And finally, the output

{
  "search": "search_string",
  "category": "socks"
}

You can also do $category = $request::get('category'); to get only the category as a string.