P
P
Prodion2022-04-19 21:41:29
PHP
Prodion, 2022-04-19 21:41:29

How to implement filter presets (SEO filter)?

There is a desire to make the simplest rating of services.

Functionality:

1. All services are displayed on the main page.
2. If the user used the filter, then we display services that meet the user's conditions.
3. If a preset has been assigned to the filter, then we do a redirect.

Three tables. Services , Features , and Presets . The preset is determined by get-parameters ( Country=1&Lang=2). That is, either we simply filter the services, or we redirect to a preset and there will be a different logic.

Sketched out some code. I can’t vouch for performance, because I didn’t check it. I just wrote in order to at least approximately understand the logic.

class ServiceController extends Controller
{
    public function index(Request $request)
    {
        $services = Service::where('active', true);
        $features = $request->query();

        if ($features) {
            $preset = Preset::where('features', $features)->first();

            if ($preset) {
                return redirect()->route('preset', [
                    'preset' => $preset->slug
                ]);
            }

            $services->whereHas('features', function ($query) use ($features) {
                foreach ($features as $key => $value) {
                    $query->where($key, $value);
                }
            });
        }

        return view('index', [
            'services' => $services->get()
        ]);
    }
}


1. Accordingly, problem number 1 Preset::where('features', $features)->first();. We have an array here, and we where()need a string. How can this be overcome?
2. You can write Country=1&Lang=2and Lang=2&Country=1. It turns out that in one of the options it will not work. It's also not clear how to overcome it.

I would appreciate any help on this. Ideas, code remarks, suggestions, etc - thanks in advance for everything!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pLavrenov, 2022-04-19
@PRodion

Problem 1) you can make a string from an array, http_build_query()
Problem 2) You can sort the array alphabetically at the time of adding to the database and at the presence check in the database, and then the order will not be important.
Problem 3) $features = $request->query(); it would be better to use validation instead.

J
JhaoDa, 2022-04-19
@JhaoDa

1. Store an array.
2. Sort.
3. Read the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question