CristalTeam/php-api-wrapper

Working with 'like' queries

BMasquio opened this issue · 1 comments

How to work with like queries?

I'm working with two applications, A and B. B uses A's models through this wrapper.

Take Post as the model I'm working on. I understand that Post::where('X','Y')->get() clauses are sent through the APIs in query string as <url>/posts?X=Y and I can implement the where query in A's PostController.

public function index(Request $request)
    {
        $queryString = $request->query;
        $query = Person::query();

        foreach($queryString as $key => $item){
            if($key != 'limit') {
                $query->where($key, $item);
            }
        }

        return $query->get();
    }

Nevertheless, when I use Post::where('X','like','Y')->get(), it looks like the API is called as <url>/posts?X=like. Am I using it correctly? Does this wrapper consider 'like' queries?

TZK- commented

Generaly search endpoint in API will not work 'out of the box' like something you could do with Eloquent, at least if your search endpoint has implemented some more complex search operation, such as like or relationnal operator (>, <, =, etc.).

Since the API Wrapper only forwards calls to an API Endpoint, this library cannot by itself know how you would pass the query parameters to the API.

So what could you do instead ?

Let's assume you have an endpoint :

GET /posts?title=the-string-i-search-for&operator=like
or
GET /posts?title[like]=the-string-i-search-for
or whatsoever...

Implemented for example like this :

class PostController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->get('title');
        $operator = '=';

        if ($request->get('operator') === 'like') {
            $operator = 'like';
            $search = "%$search%";
        }

        return Post::query()
            ->where('title', $operator, $search)
            ->paginate(10);
    }
}

You will be able to query this endpoint via the API Wrapper such as

Post::where('title', 'the-string-i-search-for')->where('operator', 'like')->get();

where you send the proper parameters (splitted into title & operator arguments).

If you have ideas to improve this part, feel free to share your mind !