I’m building a Laravel Nova project and would like to integrate Fancybox to display an image gallery with lightbox and slider functionality. I have a field (stored as a JSON array of image paths) that I want to render as clickable thumbnails. When clicked, the thumbnails should open in a Fancybox modal with navigation (slider) support.
I plan to load Fancybox’s assets (CSS and JS) via Nova’s asset-loading methods (using Nova::style and Nova::script) and initialize Fancybox using a custom JavaScript file. My expectation is that the images will open in a modal lightbox with slider functionality instead of simply navigating to the image URL.
What I Tried:
Loading the Assets in NovaServiceProvider:
In my app/Providers/NovaServiceProvider.php, I load Fancybox (and jQuery, since Fancybox 3 depends on it) as follows:
use Laravel\Nova\Nova;
use Laravel\Nova\Events\ServingNova;
public function boot()
{
parent::boot();
Nova::serving(function (ServingNova $event) {
// Load Fancybox CSS
Nova::style('fancybox', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css');
// Load jQuery first (Fancybox depends on it)
Nova::script('jquery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js');
// Load Fancybox JS
Nova::script('fancybox', 'https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js');
// Load custom initialization script
Nova::script('fancybox-init', asset('js/fancybox-init.js'));
});
}
Initializing Fancybox in a Custom Script:
I created a file at public/js/fancybox-init.js with the following content to bind Fancybox to elements with a data-fancybox attribute:
$(document).ready(function() {
// Bind Fancybox to any element with the data-fancybox attribute
$('[data-fancybox]').fancybox({
loop: true, // Enable looping of gallery images
// You can add additional options here
});
});
Rendering the Gallery in a Nova Resource:
In one of my Nova resources, I output a gallery using a Text field that decodes a JSON array of image paths:
use Laravel\Nova\Fields\Text;
Text::make('Images', 'image')
->displayUsing(function ($value) {
$images = json_decode($value, true);
if (empty($images)) {
return 'No images available';
}
$html="';
return $html;
})
->asHtml();
I expected that clicking any thumbnail in the Nova resource would trigger Fancybox to intercept the click event, opening the image in a modal lightbox with slider navigation. Instead, I’m not sure if the integration is working as intended or if there are any Nova-specific considerations (such as dynamically loaded content or asset caching) that I need to address.