0

How to perform queries in the Eloquent Laravel 6 database using "or" in columns of the same table?

Example: I want to search for the word "coffee" in the "products" table in name, description and ean1 columns. how do I do this using Eloquent?

1 Answers1

1

You can do something like this:

$search_str = 'coffee'

$filter = Product::where('name', 'LIKE', '%' . $search_str . '%')->orWhere('description', 'LIKE', '%' . $search_str . '%')

Asif
  • 350
  • 2
  • 10
  • And for more than 2 columns? – Rafael Furtado Feb 05 '20 at 20:30
  • you can add as many `orwhere` functions next with the same query – Asif Feb 05 '20 at 20:32
  • That third column is from same table too? Please share that query? – Asif Feb 05 '20 at 20:37
  • Yes, same table. $search = request()->query('query'); $products = Produto::where('name','LIKE',"%{$search}%") ->orWhere('description','LIKE',"%{$search}%") ->orWhere('ean1','LIKE',"%{$search}%") ->orWhere('ean2','LIKE',"%{$search}%") ->orderBy('id', 'asc') ->paginate($per_page); – Rafael Furtado Feb 05 '20 at 20:42
  • Look like your query is correct but lets do this, remove all where functions and check if your query return anything? other thing is to print the query and tested it directly in phpmyadmin and see if it works correctly? – Asif Feb 05 '20 at 20:47
  • also make sure `$search` variable is not empty? – Asif Feb 05 '20 at 20:52