Geoff_S
Geoff_S

Reputation: 5107

Vue returning data objects from axios call to controller

I'm using vue in laravel and trying to get a controller function that I'm hitting to return the data so that I can use it in the data() section of my vue template.

I know the controller function returns what I need, but I'm not so sure how I need to handle the return/response in the axios call in order to start placing the data into the data() function in vue

Blade/Vue template

import moment from 'moment'
export default {
    name: 'calendar',
    data () {
        return {
            events: [
                {
                    title: 'test',
                    allDay: true,
                    start: '2019-08-17',
                },
            ],
            config: {
                defaultView: 'month',
                eventRender: function(event, element) {
                    console.log(event)
                }
            },
        }
    },
    created() {
        this.fetchTasks();
    },
    methods: {
      fetchTasks() {
        axios.get('/landing/tasks' )
            .then((response) => {
                // handle success
                this.assetOptions = response.data;
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
            .finally(function () {

        });
    }
}
}

Route

Route::get('/landing/tasks', 'landingController@getTasks')
    ->name('landing/tasks');

Controller

public function getTasks()
{
    $getTask = Task::getTaskForLanding();

    $result = array();
    foreach($getTask as $id => $task){
        $result[$task->taskt_id][] = $task;
    }
}

Upvotes: 0

Views: 816

Answers (1)

Maksim Ivanov
Maksim Ivanov

Reputation: 4311

If you are certain that the Controller returns what you need, the only thing you are missing is declaration of assetOptions. To be able to assign response.data to assetOptions later on, you have to declare it in the data function first.

data() {
    return {
    ...
    assetOptions = []; // assuming you are expecting an array
    ...
    };
}

Once that is done, you are all set.

Upvotes: 1

Related Questions