DEV Community

Cover image for Dynamic queries with Laravel
Rafael França
Rafael França

Posted on • Originally published at Medium

Dynamic queries with Laravel

When developing a project for a client, a doubt arose: how create a dynamic query using only Eloquent?

Maybe, you can think: “It’s easy! We can use the method when”.
But that wasn’t what I intended, therefore, before continue, let me show you better the problem.

Imagine that I have a schedule, and I need create an event that start and finish with a difference of weeks and has a repetition in specific days of week. E.g.:

I, Rafael, intent elevate my English and Spanish level, therefore, intent study English by one hour, in every Sunday, Wednesday and Friday, during a one month; and, Spanish, every Tuesday, Thursday and Saturday.

Now, imagine that you receive the dates using a numeric representation, in that 0 is equals a Monday, and 6 is a Saturday, thus we can represent the received data by the vector below:

{
    "frequency": "daily",
    "days": [1, 3, 5],
    "date_start": "29/05/2020",
    "date_end": "29/06/2020",
    "hour_start": "20:00",
    "hour_end": "21:00"
}
Enter fullscreen mode Exit fullscreen mode

As every people that want to study, not like be interrupted to make another thing, therefore, we need grant this event not collide with another. So, more one time, how make this, using only Eloquent?

The response is simple. See above:

[...]

})->when(request()->get('frequency') === "daily", function (Builder $subquery) {
    foreach (request()->get('days') as $day) {
        $subquery->where('days', 'LIKE', "%$day%");
    }
    return $subquery;
});

[...]
Enter fullscreen mode Exit fullscreen mode

What do you think about the tip?

Soon I back with more! :)

PS: Originally posted on my account on Medium.

Cover photo by Chris Ried on Unsplash.

Top comments (0)