A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving necessary data.

Although I have been able to pass the arrays as strings, I would prefer not to transform them back into arrays within the controller.

I am wondering if there is a way to achieve the same result but directly passing the arrays instead of converting them into strings first. Is this feasible at all?

Here's the Axios call made from Vue:

$rutas = ["01", "02"];
$tipos = ["01", "03", "04"];

var params = new URLSearchParams();
params.append("rutas", $rutas);
params.append("tipos", $tipos);

var request = {
  params: params
};
axios.get('/test/', request);

Defined route:

Route::get('/test/', 'TestsController@getClientesPorRuta');

This snippet showcases the method within my controller:

public function getClientesPorRuta(Request $request) {
  $rutas = $request->input('rutas');
  $tipos = $request->input('tipos');
  
  // The following code illustrates the issue faced when attempting to access array elements
  $index = 0;
  $register = Ruta::where('CODIRUTA','=',$rutas[$index])->first();
}

Answer №1

you don't need to convert the array to a string in order to pass it, you can simply pass it directly.

var request = {
  rutas: $rutas,
  tipos: $tipos,
};
axios.post('/test/', request);

It's recommended to use axios.post instead of axios.get because the get method uses the URL to pass data and URLs cannot contain arrays, so they are converted to strings (like '1,2').

Also, make sure to change Route::get to Route::post in your routes file.

Route::post('/test/', 'TestsController@getClientesPorRuta');

Now in your PHP code, $request->rutas is already set as ["01", "02"].

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Geolocation in HTML5 and JavaScript

Currently, I am working on my debut mobile web application and have successfully integrated Google Maps into it using Geolocation JavaScript API version 3. Now, I am looking to add a button that, when clicked by the user, centers the map on my location o ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

I am experiencing difficulty with the function from flip.to not functioning properly on my Next.js project

I was given this script by flip.to <script> !function(b,e){ (b[e] = b[e] || []).push({ flipto: { bookingEngine: "Demo", companyCode: "XX", code: "YYYY", ...

Tips on including a CDN stylesheet into the Cypress component test runner

Within my vue-cli project, I have successfully set up the cypress component test runner by following the official documentation available at https://docs.cypress.io/guides/component-testing/introduction. However, I am facing an issue with using icon fonts ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Integrate PEM certificate into an Http Request with AngularJS/NodeJS

Currently, I am working on an application that requires retrieving data from a REST endpoint within an encrypted network. Accessing this data is only possible by physically being present (which is currently not an option) or using a PEM certificate provide ...

Updating the input value in a React application

With a list and an edit button, upon clicking the edit button, a new modal opens. How can I auto-populate the selected username email? The server-side response is {this.test.name}, where I provide him with the input value to auto-populate. However, when ...

Techniques for merging two arrays with commas in PHP

Is there a way to concatenate two array values with a comma in between? Below is the code snippet: <?php $abc=array( 'Title' => 'mr', 'FirstName'=> 'fname', 'Middlename'=> &ap ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

Tips for resolving the issue of the symbol ' displaying as &#39 in an Angular 2 application

I am currently working on an Angular application that makes API calls when a name displayed in a grid table is clicked. However, I have encountered an issue where names containing an apostrophe are being displayed incorrectly as &#39 instead. I managed ...

Discover the latest data in the Laravel and Vue.js integration

My edit page is located at: http://localhost/smp/post/12 https://i.stack.imgur.com/5KAbo.png API ROUTE: Route::get('package', [ProductController::class, 'update']); In ProductController.php public function update(Request $request) { ...

The build process encountered an error due to the absence of ESLint configuration after the import

Having recently worked on a Vue project created using Vue CLI, I found that eslint was also included in the project. Although I haven't utilized eslint much up to this point, I understand that it is beneficial for catching stylistic errors, semantic e ...

What is the best way to transpile when using vue-cli-service to build a library?

Currently, I am in the process of creating a library primarily consisting of .vue components for reusability across various projects (not intended for public npm use) using vue-cli-service. Everything appears to be set up correctly, and I can confirm that ...

"Utilizing Vue-router to dynamically update meta tags based on route properties

I'm facing an issue with changing the meta attribute in my .vue file. Currently, I am only passing the id property, but I want the name to be set using meta.name. I attempted to implement the solution suggested by Phil (here), but unfortunately, it di ...

Something seems to be amiss with the Vue.js eslint configuration. Can you help

I am just starting out with vueJs. I attempted to use this basic code in my vue project to update the data of a component: <template> <div> <h1> {{ message }} <h2> Hello {{ firstname }} {{ lastna ...

The ternary operator is malfunctioning when it comes to the condition

I've encountered an issue while trying to integrate a custom MUI button into my project. My goal is to have the button enabled only when 2 specific objects are not empty, otherwise it should remain disabled. Despite my efforts, the code I've writ ...

I am looking for assistance constructing a task management application using vue.js

I am facing an issue with developing a to-do list using Vue.js. The goal is to add tasks to the list by entering them and clicking a button. Once added, the new task should show up under "All Tasks" and "Not finished". Buttons for marking tasks as " ...

Dealing with the Token Mismatch Issue in AJAX Requests with Laravel 5

I am having trouble creating an AJAX call in Laravel 5. Every time I try, I encounter a TokenMismatchException but I can't figure out the reason why. This is my AJAX code: $(document).ready(function() { $("#send").click(function() { ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

"Understanding How to Utilize the Grpc Stream Variable for Extended Processes in Node.js

Utilizing Node.js for connecting to a server through gRPC in order to execute a lengthy task. The server sends a one-way stream to the client (Node.js app) while the task is ongoing. I am looking to add a Stop button and have been advised that closing the ...