Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mleontenko's avatar

Using JavaScript libraries in Laravel view components (6.x)

I'm trying to add leaflet.js map to my laravel project.

Leaflet is installed via

npm install leaflet

After that, I used this to compile assets:

npm run dev

I have a view (map.blade.php) in which I'm trying to use leaflet like this:



<!DOCTYPE html>
<html>
<head>
    
    <title>Quick Start - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
</head>
<body>



<div id="mapid" style="width: 600px; height: 400px;"></div>

<script>

    var mymap = L.map('mapid').setView([51.505, -0.09], 13);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(mymap);

    L.marker([51.5, -0.09]).addTo(mymap)
        .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();

    L.circle([51.508, -0.11], 500, {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5
    }).addTo(mymap).bindPopup("I am a circle.");

    L.polygon([
        [51.509, -0.08],
        [51.503, -0.06],
        [51.51, -0.047]
    ]).addTo(mymap).bindPopup("I am a polygon.");


    var popup = L.popup();

    function onMapClick(e) {
        popup
            .setLatLng(e.latlng)
            .setContent("You clicked the map at " + e.latlng.toString())
            .openOn(mymap);
    }

    mymap.on('click', onMapClick);

</script>



</body>
</html>


I'm getting the following error: Uncaught ReferenceError: L is not defined at map:25

Now, I understand that this is because leaflet library is not loaded properly, but I don't know what is the best way to load it so I can use it in this view?

0 likes
1 reply
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@mleontenko add require('leaflet'); to resources/js/app.js, then in your layout file load compiled app.js:

<script src="{{ asset('js/app.js') }}"></script>

1 like

Please or to participate in this conversation.