I’m trying to search the entire row of my database for the user’s searchbar input. The code I have returns an empty set:
$posts = Post::where([
['title', 'LIKE', '%'.$search.'%'],
['description', 'LIKE', '%'.$search.'%'],
['intro', 'LIKE', '%'.$search.'%'],
['row_1_heading', 'LIKE', '%'.$search.'%'],
['row_1_body', 'LIKE', '%'.$search.'%'],
['row_2_heading', 'LIKE', '%'.$search.'%'],
['row_2_body', 'LIKE', '%'.$search.'%'],
['row_3_heading', 'LIKE', '%'.$search.'%'],
['row_3_body', 'LIKE', '%'.$search.'%'],
['row_4_heading', 'LIKE', '%'.$search.'%'],
['row_4_body', 'LIKE', '%'.$search.'%'],
['row_5_heading', 'LIKE', '%'.$search.'%'],
['row_5_body', 'LIKE', '%'.$search.'%'],
['conclusion', 'LIKE', '%'.$search.'%']
])->get();
This is returning a blank space in my search.blade.php. What should the proper query look like?
I need it to say:
Search and return the user's input in the title, description, intro, row_1_heading, etc...
The query below works but only for the title:
$posts = Post::where('title', 'LIKE', '%'.$search.'%')->get();
4
Answers
If you want to find posts where any of the fields contain the search term, you should use
orWhere
instead ofwhere
.you should use
orWhere()
for each condition instead of using only onewhere()
Like this :You’re using the correct syntax. There is nothing wrong with it. The query that you made states that the input must be available in every column of database. Means, if the input is "test", it should be available in title, available in description, available in intro… etc. Which might not be the case.
I think you meant to use
OR
clause in your query. You can do that by usingorWhere()
, you can read more about it here in official documentation.