Monday, May 22, 2017

How to integrate Laravel with Vue.js in a Restful API application?

Imagine a resource Post that you can perform CRUD on using a Restful API:

// in routes/api.php ...

GET     /api/v1/posts           API\V1\PostController@index
POST    /api/v1/posts           API\V1\PostController@store
GET     /api/v1/posts/{post}    API\V1\PostController@show
PATCH   /api/v1/posts/{post}    API\V1\PostController@update
// etc.

As you can see, each endpoint is handled by a controller action in Controllers\API\PostController, such as index, store, show, update, etc., as per Laravel conventions. Now, there's also a front-end dedicated controller, Controllers\PostController whose only responsibility is respond to one route /posts (in routes/web.php) and render a view:

public function index()
{
    return view('posts.index');
}

In turn, this index.blade.php has many Vue components, one that GETs and lists all Posts from the API using Axios, one that POSTs and creates a new Post object, and others to update, delete, etc. Now, the problem is, how do I organize and name these components? Here's my shot:

  • Under assets/js/components, I created a posts folder, and added index.js, show.js, create.js, update.js, etc., mimicking the Blade views that I would have otherwise created in a traditional Laravel app;
  • Each file follows a standard...

    module.exports = {
        data() {
            return { /* data here */ };
        },
        created() {
            /* processing here */
        }
    }
    
    
  • ...and is registered in assets/js/app.js following a <resource_name-action> pattern:

    Vue.component('post-index', require('./components/posts/index.js'));
    
    
  • Lastly, components are used in index.blade.php as inline templates:

    <post-index inline-template>
        <!-- HTML markup here -->
    </post-index>
    
    

Questions

  1. Would this structure comply with recommended practices in Vue / Laravel?
  2. Is it salable enough? Are component / file names semantic and/or standard?
  3. Are there aspects that I neglected? Is it productive to have your views communicate with your API and DB in a single app? Or should they be split into two apps, one for front-end, another for back-end?


via Alex

Advertisement