E
E
Evgeny Khripunov2018-06-28 22:37:52
Laravel
Evgeny Khripunov, 2018-06-28 22:37:52

How laravel to pass data from controller to component vue.js for spa?

There is an api route:

Route::namespace('Api')->group(function () {
    Route::get('/articles', '[email protected]');
});

The controller has a regular function that returns article data from the database
public function index()
    {
        return Articles::orderBy('id', 'desc')->Simplepaginate(10);
    }

In normal view: index.blade I can display data
$article->description
$article->created_at,
$article->author->name  (Тут через связь в модели можно получить автора статьи)

In the vue component, I make an axios request to the api and get the data back:
export default {
        data() {
            return {
                articles: null,
                error: null,
                loading:false,
            };
        },
        created() {
            this.fetchData();
        },
        methods: {
            fetchData() {
                this.error = this.users = null;
                this.loading = true;
                axios
                    .get('/api/articles')
                    .then(response => {
                        this.loading = false;
                        this.articles = response.data.data;
                    }).catch(error => {
                    this.loading = false;
                    this.error = error.response.data.message || error.message;
                });
            },
        },

Further, like this, for example, you can display the data of the article itself in vue
v-for="{description,created_at } in articles" ... {{ description }}

But how to get the data of the author of the article? Analogue ($article->author->name)
That's not how it works articles.author.name or author.name
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-06-28
@fannyfan414

Further, like this, for example, you can display the data of the article itself in vue
And yet, you won’t believe it, it’s possible in another way:
Accordingly, the author of the article will be available as a.author.name(unless, of course, you are not deceiving about the data structure).
Well, or by analogy with description and created_at, do it through destructuring (by the way, who advised you to do this? - you would read the official documentation instead):
In this case, it author.namewill be OK.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question