What is the most efficient way to transfer data from PHP Laravel to Vue.js and automatically update a Vue.js component whenever the data is modified?

New to Vue.js and feeling a bit lost about how reactivity works with it. I want to send data from PHP Laravel to a Vue.js component and have the component update automatically when the data changes.

I've come across suggestions on Stack Overflow recommending the use of props to pass data from a Laravel Blade template to a Vue.js component. An example can be found here.

While I got this initial setup working, I'm stuck on how to make the component update dynamically when the data changes post page-load.

My specific scenario involves a report table on a web page where user interactions trigger an Ajax call to a Laravel controller action that fetches new data for the report from the database.

The updated data, available as a PHP array or JSON, is successfully passed to the client-side JS. However, I am unsure how to notify the Vue.js component responsible for rendering the report to re-render based on the new data received. Is there a method to "update props" so Vue.js recognizes the change and automates the re-rendering process?

This is where my research has hit a dead end. Any guidance would be much appreciated. Thank you.

Answer №1

Are you utilizing Ajax outside of the Vue component or within it as a method?

I have an instance of how I dynamically refresh the Vue data from inside the component itself. Although I am unsure about allowing external JS to directly update the Vue component, exploring this option could be beneficial. In my case, I use axios instead of traditional Ajax (Axios is automatically included in most Laravel installations post version 5.5).

<template>
    <div>
        <div id="reports">
            <!-- Displaying data -->
            {{ reports }}
        </div>
        <button @click="refreshReports">Refresh</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                endpoint: '/api/MY_ROUTE/'
            };
        },

        props: {
            reports: Object
        },

        methods: {
            // Making Axios call to API endpoint
            refreshReports() {
                // GET request
                axios.get(this.endpoint)
                    .then(({data}) => {
                        this.reports = data.data;
                    });

                // POST request
                axios.post(this.endpoint, {
                    KEY: 'VALUE',
                }).then(({data}) => {
                    this.reports = data.data;
                });
                
                /*
                    `data.data` assumes the returned response is a JSON Resource

                    If incorrect data is being returned, add a `console.log(data)` to analyze the output!
                 */
            }
        }
    };
</script>

In your routes/api.php file, ensure there is a route similar to:

// GET request
Route::get('MY_ROUTE', 'ReportController@getReports');

// POST request
Route::post('MY_ROUTE', 'ReportController@getReports');

Your Controller should contain a method like:

// app/Http/Controllers/ReportController
public function getReports(Request $request) {
    return Reports::all();
}

Does that clarify things?


Update:

I'm uncertain about having an external JS script directly update the Vue component

You can import external JS scripts and utilize their functions within methods, although I have not personally implemented this before.

Something along the lines of:

<script>
import { myFunction } from '../external.js'

export default {
    methods: {
        refreshReports() {
            // Unsure if this approach is correct, merely a suggestion!
            this.reports = myFunction();
        }
    }
};
</script>

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 the arrow keys to navigate through a list of items without using jQuery

Exploring ways to develop a basic autocomplete feature without relying on third-party dependencies has been my recent project. So far, I have managed to populate a results list using an ajax call and complete fields with mouse onclick events for each optio ...

What steps should be taken to fix an "empty delimiter" error in a strpos() function?

Noticed an issue: PHP 5.2+ Warning: strpos() [function.strpos]: Empty delimiter in /helper.php on line 445 and this is the snippet of code at that specific line: if($src = $img->getAttribute('src') AND strpos($src,$fgParams->get(&apos ...

Guidelines for launching a Vue.js application in a production environment using the package-lock.json file

Looking to create a vue.js app for production using npm ci. Should the @vue/cli-service be placed in the devDependencies section of package.json before running npm ci vue-cli-service --mode production Or should the @vue/cli-service be added to the depende ...

Tips for setting up resource=>value storage in PHP

When attempting to associate an array with a resource id as the key, such as linking two values in an associative way, a warning is triggered about "Strict standards" and the resource being "cast to integer". How can one effectively link these values in ...

Assign the value to the data property once the promise has been fulfilled

When developing my app, I encountered a challenge of connecting to the MySQL backend using Sequelize. Here is the code snippet that I am currently working with: export default { data () { return { username:'' ...

Steps for enabling (almost) unidirectional communication from a client to a server

Is there a request method in Javascript that allows me to send message m and data v to the server without having to deal with the response? If not, what is the best way to return a minimally acceptable string back to the client, which will not be processed ...

Use vanilla JavaScript to send an AJAX request to a Django view

I'm attempting to make a GET AJAX request to a Django view using vanilla JS. Despite passing is_ajax(), I am having trouble properly retrieving the request object. Below is my JavaScript code. Whether with or without JSON.stringify(data), it does not ...

Retain Page Information When Refreshing Using $_POST

<!DOCTYPE html> <html lang="en"> <head> <h1>Custom Table Generator</h1> </head> <body> <center><a href = "<?php $_SERVER['PHP_SELF']?>">Refresh</a></center> <?php ...

Sending post back data to PHP variable using jQuery AJAX

In my current script, I am using jQuery to generate the days in a month. However, I would like to pass the data returned from a POST request to a PHP for loop as a condition. This will allow me to accurately populate a selection box with the correct number ...

I am unable to view the Vuex state in components nested within v-tabs until the initial visit

Using the following dependencies: vuetify: ^2.5.10 vuex: ^3.6.2 vue: ^2.6.14 I have a project that utilizes v-tabs with a child component embedded in the first tab. Within this component, I have implemented a file input field and a button to ...

Issue encountered while attempting to execute the command "vue-cli-service serve" using Vue 3

ISSUE ENCOUNTERED During an attempt to update packages, I executed ncu -u, followed by npm install to apply the updates. However, I encountered difficulties as it seemed to cause problems with eslint. Despite trying to reproduce the error for further inve ...

Guide: Installing Vuetify 2.5.6 on Vue 3

take a look at the code snippet from my main.js file: import { createApp } from 'vue' import vuetify from './plugins/vuetify' import App from './App.vue' const app = createApp(App) app.use(vuetify) app.mount('#app' ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...

Setting up webpack encore for async and await in a Symfony 4 and VueJs project

After setting up a VueJs project within Symfony 4, I encountered an unexpected error involving await and async (Uncaught ReferenceError: regeneratorRuntime is not defined) I've come across plenty of resources for webpack, but nothing specifically for ...

JSON: Automatically choose the radio button based on the provided response

Is there a way to automatically select the checked state of radio buttons based on data retrieved from a database? I need to populate this form's radio button with data <div class="col-md-4"> <label> <input type="radio" name="m ...

Querying data from multiple tables in a PHP MySQL database with more than two tables

Here is a query that retrieves paginated articles from the database along with the number of "hearts" for each article: $MySQL = ' SELECT SQL_CALC_FOUND_ROWS a.id, a.address, a.autor, a.date_created, a.time_created, a.date_edited, a.time_edit ...

What could be causing my Vuetify Stepper Component to be hidden?

I am utilizing Vue and Axios to display data using the Stepper Component from Vuetify. However, after adding the API data, it seems that the CSS class is somehow being set to display: none;. I am confused as to why this is happening, so any help would be g ...

What is the best way to use `JSON.parse` in jQuery to accommodate older browsers?

Is there a way to internally call the function in jQuery that performs JSON.parse? I need to support IE8 and IE9, which don't have JSON.parse available. This means I can't simply use it in my code, so I'll have to rely on an external librar ...

run yarn serve in the background

Is there a way to configure gitlab CI/CD for Cypress e2e testing on a Vue app that uses Yarn for package management? The Cypress documentation is focused on npm, making it difficult to adapt. You can find the official Cypress GitLab CI/CD configuration tut ...

PHP Laravel middleware WithoutOverlapping job - should not be used until properly initialized

I'm currently working with Laravel 8 and PHP 7.4, trying to integrate a job that utilizes the "WithoutOverlapping" middleware. When I dispatch the job onto a queue with the argument "1", I encounter the following error when the job runs on the queue: ...