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

mateoghidini's avatar

Whats is the best way to consume an api using ajax with laravel?

I am having issues planning de flow of my application. I have MetricHistoryRun, Category, and Strategy models with their corresponding Controllers, Seeders, etc.

I have a view which is a form for the user to enter a url, select multiple categories, and select one strategy. With the data sent through the form i´ve been requested to consume the google pagespeed insights api.

How should i do this? Should i proccess the data in any controller first? Or should i send it directly to my js file to do the ajax?

This is my view:

 @extends('layouts.app')

 @section('content')
           <div class="form-group">
               <label class="field-label">Categories</label>
               <div class="categories-container">
                   @foreach($categories as $category)
                       <div class="form-check">
                           <input type="checkbox" class="form-check-input" id="category{{ $category->id }}" name="categories[]" value="{{ $category->id }}">
                           <label class="form-check-label" for="category{{ $category->id }}">{{ $category->name }}</label>
                       </div>
                   @endforeach
               </div>
           </div>

           <div class="form-group">
               <label class="field-label" for="strategy">Strategy</label>
               <select id="strategy" name="strategy" class="form-control">
                   @foreach($strategies as $strategy)
                       <option id="strategy{{ $strategy->id }}" value="{{ $strategy->id }}">{{ $strategy->name }}</option>
                   @endforeach
               </select>
           </div>

       </div>
       <button type="submit" class="btn btn-primary">Submit</button>
   </form>

And this is my js:

$(document).ready(function() {

  });


function getPageSpeedInsights() {

const form = document.querySelector('.metrics-form');


const formData = new FormData(form);


const url = formData.get('url');


const categories = Array.from(formData.getAll('categories[]'));


const strategy = formData.get('strategy');

console.log('URL:', url);
console.log('Categorías:', categories);
console.log('Estrategia:', strategy);


$.ajax({
    url: '/metrics/api',
    method: 'GET',
    data: { url, categories, strategy },
    success: function(data) {
        console.log(data);

    },
    error: function(error) {
        console.error('Error:', error);
    }
}); 

}

The thing is that trough my form i am sending the ids of the categories and strategies and not the names

0 likes
6 replies
gych's avatar

What is exactly that you want to achieve?

Only send the category names via the form or the categories as object with its id and name?

mateoghidini's avatar

@gych I want to construct my url

My url is beeing built with categories ids instead of category names

this is a method in my controller

public function getPageSpeedInsightsApi(Request $request)
    {
        $url = $request->input('url');
        $categories = $request->input('categories');
        $strategy = $request->input('strategy');

        $categoryNames = [];
        foreach ($categories as $id) {
            $category = Category::find($id);
            if ($category) {
               $categoryNames[] = $category->name;
            }
        }
    
    

        // Construct URL
        $API_URL = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
        $params = [
            'url' => $url,
            'key' => 'env.API_KEY',
            'category' => implode(',', $categories),
            'strategy' => $strategy,
        ];

        //HTTP Request
        $client = new \GuzzleHttp\Client();
        $response = $client->request('GET', $API_URL, ['query' => $params]);

        //Convert response into array
        $data = json_decode($response->getBody()->getContents(), true);

        //Return response as json
        return response()->json($data);
    }
gych's avatar

@mateoghidini Why not use $category->name as value instead of id in your form?

    <input type="checkbox" class="form-check-input" id="category{{ $category->id }}" name="categories[]" value="{{ $category->name }}">
gych's avatar

@mateoghidini But from what I see in your code you are not storing anything new in the db with this action. You are just fetching (find) existing categories by id to get the category names from your db?

For your current code you can add the category names array instead of the $categories variable that holds the ids.

        $params = [
            'url' => $url,
            'key' => 'env.API_KEY',
            'category' => implode(',', $categoryNames),
            'strategy' => $strategy,
        ];
1 like

Please or to participate in this conversation.