Search code examples
laravelmodel

Laravel displaying model results based on a search query


I have Laravel medicines table in which medicine names are stored as

description = Verapamil 120mg tablets (IVAX Pharmaceuticals UK Ltd)
description = Verapamil 80mg tablets (Accord Healthcare Ltd)

The user can query the database like "vera 10mg" and "vera 120" The user can write part of a word instead of full word to get the result.

Example when user type "vera 80" the result should be: "Verapamil 80mg tablets (Accord Healthcare Ltd)"

Example: Type "ator 80 tev" for "Atorvastatin 80mg tablets (Teva brand)"

Right now i am getting data with where clause and the user has to type full medicine name to get the results instead of part of it.

$data = DMD::where('description','like', '%'.$query.'%');

Solution

  • This should work, though I haven't been able to verify this on a dummy server.

    $query = "vera 80";
    $queries = [];
    foreach (explode(" ", $query) as $word) {
        $queries[] = ["description", "LIKE", "%$word%"];
    }
    $data = DMD::where($queries);
    

    From the documentation, this is going to create an array of AND WHERE clauses.


    Another alternative is the below.

    $query = "vera 80";
    $data = DMD::query();
    foreach (explode(" ", $query) as $word) {
        $data->where("description", "LIKE", "%$word%");
    }
    

    This version will create a basic query object for the database table.
    Then we will split the string on spaces, and iterate through each word.

    The $data->where line is mutating the object add adding a new AND WHERE clause to the database query.


    As is the case in both examples, I haven't called the get() method on the $data object as I noticed that you didn't in your example.
    Naturally, if you want to get your results you'll need to call this otherwise you'll just have a Builder instance.