Laravel : How to get random image from directory?
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/imagesif($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.