Consume Laravel APIs from VueJS with Passport

Laravel 5.6 suggests a simple structure for creating API-driven applications. Your API routes are declared in their own routes/api.php file, and can leverage the auth:api Middleware for security. By default, the system uses the built-in API TokenGuard for that, which requires you to come up with your own system for issuing tokens against users. Passport offers a simpler way that doesn’t require you to use the entire system.

Five steps!

To implement this into an existing Laravel project, there’s only a few edits you need to make: 1. Install Passport
$ composer require laravel/passport
Out of the box, Passport sets you up for a full-on OAuth system, which we don’t really need. So to prevent it creating unnecessary tables, add the following to register() in app/Providers/AppServiceProvider:
\Laravel\Passport\Passport::ignoreMigrations();
2. Include the CreateFreshApiToken Middleware Add this Middleware to your web stack, in app/Http/Kernel:
'web' => [
    ...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
]
This will attach a JWT token called laravel_token as a cookie on all future web requests. 3. Include the HasApiToken trait on your User model
class User extends Authenticatable
{
    use Notifiable, \Laravel\Passport\HasApiTokens;
}
This trait looks for the laravel_token field and automatically logs you in if it’s detected – as long as you’re using the passport driver. 4. Use the passport driver for api auth Edit your config/auth.php to set the api driver up:
'guards' => [
  'api' => [
    'driver' => 'passport'
  ]
]
5. Generate the keys Last step, generate the public/private keys for Passport:
$ php artisan passport:keys
Passport will use these within the passport driver to generate and decode the laravel_token JWT payloads, then use that to authenticate the User model with the HasApiToken attached. From this point on, you should be able to use VueJS with your secure APIs out the box.

Sample Project

With the laravel_token cookie being set, and axios headers configured with the defaults (inside bootstrap.js):
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
Any requests you make to a route secured by auth:api will log you in automatically. route/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
resources/views/home.blade.php
resources/js/app.js
const app = new Vue({
    el: '#app',
    data: {
        user: null
    },
    mounted() {
        axios.get('/api/user').then((response) => {
            this.user = response.data;
        });
    }
});
With that all compiled and run, it’ll fetch the logged-in user object and render it out:
Cropped from the default app