How to pass data from one view to another with Vue and axios in Laravel

2

I'm working with Laravel and I have this link in view A

<div id="app">
    <a href="{{ route('ministries.index') }}">Enlace</a>
</div>

and I want to click on that link to direct it to view B and show me the results obtained by the controller.

This is the route I have:

Route::resource('ministries', 'Admin\MinistryController');

Vue code:

new Vue({
    el: '#app',
    data: {
        ministries: []
    },
    created: function() {
        this.getMinistries()
    },
    methods: {
        getMinistries: function() {
            var url= 'ministries';
            axios.get(url).then(response => {
                this.ministries = response.data
            });
        }
    }
});

Controller code:

public function index() {
    return Ministry::orderBy('id', 'DESC')->get();
}

The HTML of view B

<tbody>
    <tr v-for="ministry in ministries">
        <td>@{{ ministry.id }}
        <td>@{{ ministry.name }}
    </tr>
</tbody>
    
asked by Roman González 14.02.2018 в 03:37
source

2 answers

1

In this case it is necessary for the controller to deliver a view as response (view B):

public function index()
{
    $variable = Modelo::orderBy('id', 'desc')->get();
    return view('vista', compact('variable'));
}

As for Vue, it is not necessary to use axios (which is used to make Ajax requests), because you get the data directly from Laravel, and you have the information available in blade, you simply add the model to the data object, which It has reactivity, all this as long as you are not using components (according to your syntax, it does not seem):

new Vue({
    el: '#app',
    data: {
        ministries: {!! $variable !!}
    },
});

The template would remain as you have it:

<tbody>
    <tr v-for="ministry in ministries">
        <td>@{{ ministry.id }}</td>
        <td>@{{ ministry.name }}</td>
    </tr>
</tbody>
    
answered by 14.02.2018 / 03:53
source
0

Excellent response suggested by Shaz, would only make a small addition to your answer and is that the data should be sent from the controller in json format or when you receive the data object to pass it like this:

new Vue({
  el: '#app',
  data: {
    ministries: {!! json_encode($variable) !!}
  },
});
    
answered by 16.02.2018 в 22:34