Search code examples
laravellaravel-relations

Search using Tags in Laravel


I'm very new to Laravel and

Trying to make a search system by Tags, like I have a products table and each products have multiple tags in the product_tags table. product_tags table has two column product_id and product_tag

        $search = $req->get('search'); // Input from user 
        
        $products = Product::with(['images', 'tags'])
        ->where('id', 'LIKE' , '%'.$search.'%')
        ->orWhere('product_name', 'LIKE' , '%'.$search.'%')
        ->orWhere('product_price', 'LIKE' , '%'.$search.'%')
        ->get();

        dd($products);

Product Modal

class Product extends Model
{
    use HasFactory;

    public function images()
    {
        return $this->hasMany(ProductImage::class, 'product_id', 'id')->orderBy('id', 'desc');
    }
    public function tags()
    {
        return $this->hasMany(ProductTag::class, 'product_id', 'id')->orderBy('id', 'desc');
    }
}


Solution

  • Product::with(['images', 'tags'])
        ->where(function ($query) use ($search) {
            $query->where('id', 'LIKE' , '%'.$search.'%')
                  ->orWhere('product_name', 'LIKE' , '%'.$search.'%')
                  ->orWhere('product_price', 'LIKE' , '%'.$search.'%');
        })
        ->orWhereHas('tags', function ($query) use ($search) {
            $query->where('product_tag', 'LIKE', '%'.$search.'%');
        })
        ->get();