Laravel : How to get random image from directory? Laravel : How to get random image from directory? laravel laravel

Laravel : How to get random image from directory?


In Laravel you need to use Storage to work with filesystem.

$files = Storage::allFiles($directory);$randomFile = $files[rand(0, count($files) - 1)];


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)


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.