Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

searching on name instead of id on sql

I have search input in my products page. I can search on name on description and on category if I type the id but that’s not really practical how i change this sql so i can search on the name of the category instead of the id.

DB i have Products | name,description,category_id
Categories | id,name

    public function scopeFilter($query,array $filters){
    if ($filters['search'] ?? false){
        $query
            ->where('name', 'like', '%' . request('search') . '%')
            ->orWhere('description', 'like', '%' . request('search') . '%')
            ->orWhere('category_id', 'like', '%' . request('search'). '%');
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Since the category is a related model search on the relationship:

public function scopeFilter($query,array $filters){
    if ($filters['search'] ?? false){
        $query
            ->where('name', 'like', '%' . request('search') . '%')
            ->orWhere('description', 'like', '%' . request('search') . '%')
            ->orWhereHas('category', function ($q) {
               $q->where('name','like', '%' . request('search'). '%'
            });
    }
}

This is assuming you have defined your relationship in your model.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading