Laravel

Laravel Vue JS Axios Post Request

Pinterest LinkedIn Tumblr

In a Laravel and Vue.js application, you can use the Axios library to make a POST request to the server. Here’s an example of how you might use Axios to make a POST request in a Vue component:

<template>
  <div>
    <form @submit.prevent="submitForm">
      <input type="text" v-model="formData.name" placeholder="Name">
      <input type="text" v-model="formData.email" placeholder="Email">
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      formData: {
        name: '',
        email: ''
      }
    }
  },
  methods: {
    submitForm() {
      axios.post('/api/submit-form', this.formData)
        .then(response => {
          // handle the success response
        })
        .catch(error => {
          // handle the error
        });
    }
  }
}
</script>

In this example, the submitForm method is called when the form is submitted. The method uses Axios to make a POST request to the /api/submit-form endpoint with the form data. The form data is stored in the formData object, which is bound to the form inputs using the v-model directive.

On the server-side, in your laravel application you can define a route that corresponds to the endpoint that the frontend is posting to.

Route::post('/api/submit-form', function (Request $request) {
    // handle the form data here 
    $name = $request->input('name');
    $email = $request->input('email');
    // do something with the data
    return response()->json(['success' => true]);
});

Please note that this is just an example and you may need to adjust it to fit your specific use case. Also, make sure to use appropriate validation and sanitization on the server side to protect your application from any malicious inputs.

Write A Comment