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

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

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.

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

    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 class="form-control" type="textarea" name="search"  rows="5" cols="50" placeholder="Search..." required></textarea>
        <button class="btn btn-success pull-right" type="submit"><i class="glyphicon glyphicon-search" aria-hidden="true"></i> Search</button>
    </form>

>Solution :

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'));
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