Reputation: 321
I have a set of text files inside public/storage/
and I need to search their content, I tried to tailor this answer to work in Laravel but with no success
public function search($query)
{
$dir = new \DirectoryIterator(public_path('public'));
foreach ($dir as $file) {
return $file;
$content = file_get_contents(public_path($file));
if (strpos($content, $query) !== false) {
return 'yes';
} else {
return 'no';
}
}
}
I believe the problem with the code is that I don't know how Laravel accesses paths.
File structure in Laravel:
project
│
└───public
│
└───storage
│
│ file1.txt
│ file2.txt
│ ...
└───
Upvotes: 0
Views: 1309
Reputation: 10219
If you want to get the path to public/storage
, you need to call public_path('storage')
.
Also you could use glob()
, but that depends on your folder/file structure.
Example:
$files = glob(public_path('/storage') . '/*.txt');
This will return an array of all files that have .txt
extension in public/storage/
.
If those files are in folders inside public/storage
you need to recursively get all those files.
Upvotes: 0
Reputation: 9749
This should work the way you intent to check the contents of each file:
$dir = new \DirectoryIterator(public_path('storage'));
foreach ($dir as $file) {
if ($file->isFile()) {
$content = file_get_contents($file->getRealPath());
if (str_contains($content, $query)) {
return 'yes';
}
}
}
return 'no';
Upvotes: 3