Home > Mobile >  Search for each keyword entered in the textare based on new line
Search for each keyword entered in the textare based on new line

Time:10-26

I'm trying to build search functionality where user can submit multiple keywords each one on new line in the textarea and then perform search in database table.

The problem is with my current code that I have is searching for the last keyword only.

Here is the function that I have in my controller. I'm not sure if the query should be in the foreach loop at all.

    public function search(Request $request){

        $search = $request->input('search');

        foreach(explode("\r\n", $search) as $line) {
            $result = Posts::query()
            ->where('title', 'LIKE', "{$line}%")
            ->get();
        }
        return view('search', compact('result'));        
    }

Here is the textarea on the search blade

    <form role="form" id="form-buscar" action="{{ route('search') }}" method="GET">
        <textarea  type="textarea" name="search"  rows="5" cols="50" placeholder="Search..." required></textarea>
        <button  type="submit"><i  aria-hidden="true"></i> Search</button>
    </form>

CodePudding user response:

You need to contain like condition with foreach function instead all the query:

$search = $request->input('search');
$query = Posts::query();
foreach (explode("\r\n", $search) as $line) {
    $query->where('title', 'LIKE', "{$line}%");
}
$result = $query->get();
return view('search', compact('result'));
  • Related