Transferring information in Laravel with the help of Axios and Vue Framework

While following the Laracasts tutorial on integrating Stripe, I noticed that a lot has changed since the release of Laravel 5.4. Although I managed to navigate through most of it, I encountered an issue when trying to submit a payment form using Vue and Axios.

The product is fetched from a database and displayed in a select dropdown, which functions correctly. However, my problem arises when the data is not properly sent to the store function in the PurchasesController. Upon attempting to make a purchase, the form modal appears as expected. After filling it out with test data and submitting it, a 404 error is returned for /purchases in Chrome inspector. The network tab displays the error: "No query results for model [App\Product]."

Here is the original code snippet from Vue:

<template>
    <form action="/purchases" method="POST">

        <input type="hidden" name="stripeToken" v-model="stripeToken">
        <input type="hidden" name="stripeEmail" v-model="stripeEmail">

        <select name="product" v-model="product">
            <option v-for="product in products" :value="product.id">
                {{ product.name }} &mdash; ${{ product.price /100 }}
            </option>
        </select>

        <button type="submit" @click.prevent="buy">Buy Book</button>

    </form>
</template>

<script>
    export default {
        props: ['products'],
        data() {
            return {
                stripeEmail: '',
                stripeToken: '',
                product: 1
            };
        },
        created(){
            this.stripe = StripeCheckout.configure({
                key: Laravel.stripeKey,
                image: "https://stripe.com/img/documentation/checkout/marketplace.png",
                locale: "auto",
                token: function(token){

                    axios.post('/purchases', {
                        stripeToken:  token.id,
                        stripeEmail: token.email
                      })
                      .then(function (response) {
                        alert('Complete! Thanks for your payment!');
                      })
                      .catch(function (error) {
                        console.log(error);
                      });

                }
            });
        },
        methods: {
            buy(){
                let product = this.findProductById(this.product);

                this.stripe.open({
                    name: product.name,
                    description: product.description,
                    zipCode: true,
                    amount: product.price
                });
            },

            findProductById(id){
                return this.products.find(product => product.id == id);
            }
        }
    }
</script>

And here's the code snippet from my PurchasesController:

<?php

namespace App\Http\Controllers;

use Log;
use App\Product;
use Illuminate\Http\Request;
use Stripe\{Charge, Customer};

class PurchasesController extends Controller
{
    public function store()
    {

        Log::info("Product Info: " . request('product'));
        Log::info("Stripe Email: " . request('stripeEmail'));
        Log::info("Stripe Token: " . request('stripeToken'));

        $product = Product::findOrFail(request('product'));

        $customer = Customer::create([
            'email' => request('stripeEmail'),
            'source' => request('stripeToken')
        ]);

        Charge::create([
            'customer' => $customer->id,
            'amount' => $product->price,
            'currency' => 'aud'
        ]);

        return 'All done';
    }
}

I realized that the product wasn't being passed to /purchases above, so I attempted the following solution:

axios.post('/purchases', {
    stripeToken:  token.id,
    stripeEmail: token.email,
    product: this.product
})

Unfortunately, even after making this change, I continued to receive the same "No query results for model [App\Product]" error. Is there a different or better way to pass data from Vue/Axios that I could utilize instead? Any assistance would be greatly appreciated.

Thank you in advance.

Edit The solution was to assign this to a new variable, and it started working again. Here is the relevant part of the Vue Code that worked for me:

created(){
    let module = this; // cast to separate variable
    this.stripe = StripeCheckout.configure({
        key: Laravel.stripeKey,
        image: "https://stripe.com/img/documentation/checkout/marketplace.png",
        locale: "auto",
        token: function(token){

            axios.post('/purchases', {
                stripeToken:  token.id,
                stripeEmail: token.email,
                product: module.product
              })
              .then(function (response) {
                alert('Complete! Thanks for your payment!');
              })
              .catch(function (error) {
                console.log(error);
              });

        }
    });
},

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

What is the process for updating the package-lock.json file in Laravel?

GateLab's security feature has identified some known vulnerabilities in the package-lock.json file that need to be updated. The message states: Known security vulnerabilities detected Dependency object-path Version < 0.11.5 Upgrade to ~> 0.11. ...

Server receives an empty req.body from Axios GET request

I've been encountering an issue in my React app where Axios sends an empty request body when making a GET request. Interestingly, I have successfully made requests using Insomnia without any problems on the backend. I've attempted a few solutions ...

fetching images from the database

I am currently working on a classified website project where I want to display one photo from the database on the main page, the same photo on a category page, and then all photos when viewing the full item listing page. My goal is to have a similar setup ...

Django: Troubleshooting a 403 CSRF Error when making a post request with Vue.js and axios - "CSRF token missing or incorrect"

As a newbie in web development, I've run into a problem that I can't seem to solve easily. Currently, I'm utilizing Django 3.2.6, django restframework (DRF) 3.14, Vue 3.0, and axios for making API calls. I've created an APIView to lock ...

Vuetify: Responsive v-date-picker width for v-dialog and v-menu

I am looking to create an adaptive date picker using v-date-picker. When the page is viewed on a phone, I want the date picker to open in a v-dialog, and when viewed on a desktop, I want it to open in a v-menu. Here is my attempt: <template> < ...

Substitute the values of 1 and 0 with words in the displayed table by leveraging vue

I am a beginner with vue.js. Currently, I am using the vue.js element.io framework to render a table and fetching data from an API, which is working fine. My goal now is to display text in the 'Active' field instead of just 1 or 0. In Laravel, I ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

Using the named default export syntax in Javascript ES6+

Does this syntax meet the requirements for exporting? export default debug = { myfunction: myFunction }; ...

Updates made in MobX store are not displaying in the web browser

Why are the data changes not reflecting in the view after the api call? Here is the code snippet that might help: store.js import axios from 'axios'; import {encrypt, decrypt} from '../utils/pgp.js' import {observable, action, compute ...

The functionality of closing the image on a model popup is not functioning properly following a postback

I am encountering an issue with my ajax modelpopup extender in my webform. The CancelControlID is set to an image called imgClose. When I click on imgClose after the popup has been displayed, it successfully closes the popup. However, if I click on any co ...

What is the best method for showcasing numerous dropdown lists using JavaScript along with conditional if-else statements?

Hello everyone, I am currently new to javascript and I'm attempting to build a small web application using javascript. However, I am facing an issue with printing the drop-down list output. Could someone please assist me in resolving this problem? < ...

How can I easily activate a C# class from an asp.net webpage?

I have three labels in my asp.net page: One with a default name for filtering Another filled with a list of names to click on for new filter A third one with a list of items to be filtered The content of the second and third labels is loaded by C# code ...

Having difficulty assigning a selected value in select2 using JavaScript with Ajax mode

I am trying to use a select2 element that loads data from a database using ajax. My goal is to load the value from the database and have it selected as the default value in edit mode. However, I am encountering issues with using the trigger function to ach ...

Notification for background processing of $http requests

I am searching for a solution to encapsulate all my AJAX requests using $http with the capability to display a loading gif image during processing. I want this functionality to extend beyond just $http requests, to cover other background processing tasks a ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Tips for fixing the issue of "The use of getPreventDefault() is outdated. Please use defaultPrevented instead."

When attempting to fetch data for a specific user from an SQL Server database using JSON data, I encountered an error message in the console: "Use of getPreventDefault() is deprecated. Use defaultPrevented instead." Additionally, the values are not bei ...

Issue with redirecting after a POST request is not functioning properly

After creating an API in node and defining a method to handle POST requests, I found that returning res.redirect(redirectUrl); from the method causes the browser to redirect back to the API instead of the intended URL. Despite my efforts, this issue persi ...

Generate dynamic DIV elements and populate them with content

Can you assist me in getting this code to function properly? My goal is to dynamically create elements inside a div and fill each element with a value fetched from the database through a server-side function. I'm unsure if there's a better approa ...

Angular <select><option> tags are missing from the browser display, although they are present in the source HTML code

After incorporating a dropdown list into the FormGroup, it seems to be missing from the browser display. Upon inspecting the page's HTML source on Chrome, I noticed that the <select><option></option></select> element is present ...