问题
I have a directory containing the sub-directory, in each sub-directory there are images. I want to display the images randomly.
Below my code in php that works well, but it does not work in Laravel, problem is with opendir()
and readdir()
.
view blade
<?php
$folder = opendir('images/');
$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
$images[$i]= $file;
$i++;
}
}
$random_img=rand(0,count($images)-1);
?>
<div>
<?php
echo '<img src="images/'.$images[$random_img].'" alt="" />';
?>
</div>
回答1:
In Laravel you need to use Storage to work with filesystem.
$files = Storage::allFiles($directory);
$randomFile = $files[rand(0, count($files) - 1)];
回答2:
You can use allFiles
method of Laravel to get all the files and get one of the images using your random logic.
File::allFiles($directory)
回答3:
Actually, you can use Laravel Filesystem
but to make it completely working, you've to setup the configuration. For example, the following code will not work:
$dir = 'images'; // public/images
$files = \Storage::allFiles($dir);
Because, the Filesystem
uses configuration from config/filesystems.php
where you may have something like this:
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
// ...
]
By default, Laravel
uses local
disk and it points to a different path. So, to make it working, you've to setup your disk in the config, for example, add the following entry into the array:
'web' => [
'driver' => 'local',
'root' => base_path('public'),
],
Then, you may use something like this:
$dir = 'images'; // public/images
if($files = \Storage::disk('web')->allFiles('images')) {
$path = $files[array_rand($files)];
}
To use this $path
in your view
use <img src="{{asset($path)}}">
. Check more here.
回答4:
Here is the way to do this. I am with have now laravel 5.7, but should work for older versions too.
$files = Storage::files('path/to/directory');
$randomFile = array_random($files);
回答5:
You can use a Laravel method where you can return 1 or more random elements;
$all = Storage::allFiles($directory);
$rand = Arr::random($all, 1);
Dont forget the facade:
use Illuminate\Support\Arr;
来源:https://stackoverflow.com/questions/41166308/laravel-how-to-get-random-image-from-directory