Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel MySQL Search. Allowing users to do custom Boolean Search

I have this new requirement from client for an employee management project I am doing to allow their users to do custom boolean search.

basically allow them to use: AND, OR, NOT, brackets and quotes.

what is the best way to implement this? i have checked out mysql and they are using different syntax.

This is the test scenario:

Requirement: Search for Magicians or Barbarians having Elite or Veteran Level rank and who is from Singapore

Boolean string: ("Magician" OR "Barbarian") AND (Elite OR "Veteran Level") and Singaporean

This is one of the codes I will be consider to be modifying, which I got from Pure PHP based boolean search for strings

function booleanSearch($content, $search) {
    $criteria = str_getcsv($search, ' ');

    while ($criteria) {
        $not = false;
        $q = array_shift($criteria);

        if (substr($q, 0, 2) === '-"') {
            $not = true;

            while (substr($q, -1) != '"') {
                $q .= " " . array_shift($criteria);
            }

            $q = substr($q, 2, -1);
        }
        else if (substr($q, 0, 1) === '-' && strpos($q, ' ') === false) {
            $not = true;
            $q = substr($q, 1);
        }

        $found = strpos($content, $q) !== false;

        if ($found === $not) {
            return false;
        }
    }

    return true;
}
like image 379
RayzorMamon Avatar asked Oct 16 '25 10:10

RayzorMamon


1 Answers

You just need a query builder implementation. Based off you description it would be trivial to roll your own, otherwise, there are a number of packages out there to make life easier. Spatie's query builder works well: https://github.com/spatie/laravel-query-builder

like image 181
Brian Lee Avatar answered Oct 19 '25 00:10

Brian Lee