Home > Software engineering >  How to get all values from Laravel controller to index using JavaScript?
How to get all values from Laravel controller to index using JavaScript?

Time:04-08

I am using Laravel to get all the data from a table and show the list of coordinates for Leaflet. Currently I am working on how to use $gis in the GisController to the index's JavaScript.
So here's the GisController.php

public function index()
{
    $gis = Gis::all();

    return view('gis/map', compact('gis'));
}

and this is from the index.blade.php

foreach ($gis as $gisData) {
    //------- data from controller
    var gisType = $gisData->type;

    if (gisType == 1) {
        //------- data from controller
        var polylinePoints = $gisData->coordinates;
        var polyline = L.polyline(polylinePoints).addTo(map);
    } else if (gisType == 2) {
        //------- data from controller
        var markerPoint= $gisData->coordinates;
        var marker = L.marker(markerPoint).addTo(map);
    }
}

CodePudding user response:

have 2 ways :

  1. using ajax return object
  2. set variable into javascript
    <script>
    const gisData = <?php echo json_encode($gis); ?>;
    </script>

note : can convert $gis to array

CodePudding user response:

You could also just do a dynamic ajax hitting a Laravel api. I see you're trying to use logic in the presentation layer, should try stay away from that. You could also just send it to the front already preformatted to consume as json:

public function index()
{
    $gis = Gis::all()->toJson();

    return view('gis/map', compact('gis'));
} 

At that point on the front you don't have to do any converting and can just consume the json in your JS without having to do a bunch of php tags or blade tags.

By far in my opinion an api is the way to go on this though. So you could just hit the endpoint when data is needed, can do the logic you need to in the controller and just send the data you need to the front. I don't know how big this Gis model is but if it has tons of data you're going to see a huge performance hit constantly bringing back every row of data.
Example would be using a get() or a first() and or limit on results. I've got a table in one of my projects with over 1 million records, if I were to do a all() the server would barf all over me.

  • Related