Search code examples
laravellaravel-5vue.jsvue-resourcevue-router

Creating Show Method using vue js, vue-resource & Laravel


So i have made an api using laravel 5.2, and used VueJs to pull data from it. I was able to fetch data for the index() action by fetching all the results. Now my issue becomes little more complicated. I need to make a show() method so that each post from the table would go to it's single post page.

methods: {
        fetchItems: function (page) {
            var data = {page: page};
            this.$http.get('api/v1/pages', data).then(function (response) {
                //look into the routes file and format your response
                this.$set('items', response.data.data);
                this.$set('pagination', response.data.pagination);
            }, function (error) {

            });
        },
        changePage: function (page) {
            this.pagination.current_page = page;
            this.fetchItems(page);
        }
    }

This is my VueJs Code.

 <div class="col-md-12" v-for="post in items" track-by="$index">
            <a href="@{{ post.slug }}"><h1>@{{ post.title }}</h1></a>
            <p>@{{ post.body }}</p>
 </div>

This is my Show all posts

My questions: 1. Should i create a separate file for show method ? 2. How can i leverage laravel ioc to get $slug from post model and show single page.


Solution

  • You don't have to create a new page, however, unless you use something like Vueify, to write single file components, you may want to. It will be easier.

    The same way you created your list view, ajax call and index api, you can create a view, ajax call and api, to show our posts (using post ids). Your api response should send all the data you need to display, including the slug.

    Based on your github repository, create a route like this for your api, where id is the post id:

    Route::resource('show/{id}', 'PagesController@show');