user6780526
user6780526

Reputation:

Laravel Search Model

Im new to laravel and have completed a project on the latest version laravel 5.6

However, the only thing that is pending to learn and implement is the search functionality which is the core of every application. The application i have coded is a huge project and i do not want to mess it up so would like to learn how search functionality works in order to implement in multiple sections of the project.

Let's say i have a the following models 1.Country 2.State 3.City 4.Professional_Categories 5.Professionals and i have added the relations in the models accordingly

I fetch the records normally using the following code

public function index()
{
  $categories = ProfessionalCategory::all();
  $topprofessionals = Professional::where('status', 1)->limit(12)->get()->sortByDesc('page_views');
  $professionals = Professional::where('status', 1)->latest()->paginate(9);
  return view('professionals.index',compact('professionals', 'categories', 'topprofessionals'));
}

I can pull up Countries, States and Cities as i pulled in categories and with foreach i can display them in the select box. Or i could use pluck('name', 'id') that works good too. But i have never tried search queries.

I want a search form on the professionals page where a user can select country, state, city, category and type keywords in locality and professional name to find the professionals. My next step would be to learn dependent dropdown for country, state and city.

And how the results can be displayed on the view file where im currently fetching records with foreach($professionals as $professional)

I do not need code, but just a basic example on how these kind of things work in laravel. Once i learn the basics i want to implement auto suggest from database and things like that. And a single form to search all the models.

Upvotes: 1

Views: 11474

Answers (2)

Bogdan Cismariu
Bogdan Cismariu

Reputation: 151

Using Eloquent you might do something like this in your Controller:

public function search(Request $request)
{
    $countries = Country::where('name', 'like', '%' . $request->search_value . '%')->get();
}

This will return the countries whose name contains the search_value provided by the user.

Upvotes: 2

user320487
user320487

Reputation:

It sounds like you'll need full text searching across a number of tables and associated columns. I'd recommend using Laravel Scout or a similar service (such as elastisearch) for this.

These will index your records in a way to allow for fast and efficient fuzzy searching. Using Scout as an example, you can directly query on your models like:

$orders = App\Order::search('Star Trek')->get();

Searching with Scout

This will save you from writing numerous queries using LIKE which becomes very slow and inefficient quite quickly.

Upvotes: 3

Related Questions