25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Attaching tokens<br />

OAuth requires an access token to be sent to the frontend app when the user logs<br />

in. Passport includes a middleware that can h<strong>and</strong>le this for you. Add the<br />

CreateFreshApiToken middleware to the web middleware group <strong>and</strong> the laravel_token<br />

cookie will be attached to outgoing responses.<br />

app/Http/Kernel.php: protected $middlewareGroups = [ 'web' => [ ...<br />

\<strong>Laravel</strong>\Passport\Http\Middleware\CreateFreshApiToken::class, ], ...<br />

For outgoing requests, we need to add some headers to our AJAX calls. We can<br />

make it so Axios automatically attaches these by default. 'X-Requested-With':<br />

'XMLHttpRequest' ensures that <strong>Laravel</strong> knows the request was from AJAX, while 'X-<br />

CSRF-TOKEN': window.csrf_token attaches the CSRF token.<br />

resources/assets/<strong>js</strong>/store.<strong>js</strong>: ... axios.defaults.headers.common = { 'X-Requested-<br />

With': 'XMLHttpRequest', 'X-CSRF-TOKEN': window.csrf_token }; export<br />

default new <strong>Vue</strong>x.Store({ ... });<br />

With that done, our API requests should now be properly authenticated. To test<br />

this, let's use Tinker to see which items we have saved for our first seeded user: $<br />

php artisan tinker >>> DB::table('users')->select('saved')->first(); #<br />

"saved": "[1,5,7,9]"<br />

Make sure you're logged in as that user <strong>and</strong> load <strong>Vue</strong>bnb in the browser. Toggle<br />

a few of your saved listing selections <strong>and</strong> rerun the query above. You should find<br />

that the database is now persisting the saved listing IDs.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!