Home > OS >  Searching for all keywords with foreach and adding to the url
Searching for all keywords with foreach and adding to the url

Time:11-15

I'm trying to do my function to look up each added keyword in the search text area.

Here is the function

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

foreach(explode("\r\n", $search) as $lines) {
         
   $resource = Http::get("http://localhost:4000/keys/$lines");
        
}

return view('search', compact('resource')); 

and the form

<form id="form-buscar" action="{{ route('search') }}" method="POST">
{{ csrf_field() }}
     <div >
        <textarea  type="textarea" name="search" required></textarea>
                    
        <div >
            <button  type="submit">Search</button>
        </div>
     </div>
</form>

Simple input on the textarea

keyword
keyword1
keyword2

Currently, it gets/shows results only for the last word. What is my mistake here?

CodePudding user response:

$resource inside the foreach is only running for each iteration (each iteration is not aware of any other iteration), you want to view all the iterations so you need to append them inside the foreach and then run the final full listing outside of the foreach. You could probably use an array_walk() function.

Therefore; build an array of results and then cycle the Http::get request for each value in the array, before returning that result as a sum off all child array values:

Example

$search = $request->input('search');
// This replaces the foreach loop 
$lines = explode(PHP_EOL, $search); 
array_walk($lines, function(&$value){ 
     $value = Http::get("http://localhost:4000/keys/".$value);
   });
return view('search', ($lines?:[]));

This applies the custom anonymous function which returns the Http::get result, to each element in the array.

NOTE: as pointed out by RiggsFolly, \r\n is not quite universal for PHP line endings so using PHP_EOL is a system-aware/safe workaround to use instead.

  • Related