25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Retrieving saved items from the<br />

database<br />

Let's now work on retrieving the saved items from the database <strong>and</strong> displaying<br />

them in the frontend. To begin with, we'll add a new saved property to the<br />

metadata we put in the document head. This will be an empty array if the user is<br />

logged out, or the array of saved listing IDs associated with that user, if they're<br />

logged in.<br />

app/Http/Controllers/ListingController.php: private function<br />

add_meta_data($collection, $request) { return $collection->merge([ 'path' =><br />

$request->getPathInfo(), 'auth' => Auth::check(), 'saved' => Auth::check() ?<br />

Auth::user()->saved : [] ]); }<br />

Back in the frontend, we'll put the logic for retrieving the saved items in the<br />

beforeEach router navigation guard. The reason we put it here <strong>and</strong> not in the addData<br />

mutation is that we don't want to directly assign the data to the store state, but<br />

instead call the toggleSaved mutation for each of the listings. You can't commit a<br />

mutation from another mutation, so this must be done outside the store.<br />

resources/assets/<strong>js</strong>/router.<strong>js</strong>: router.beforeEach((to, from, next) => { let<br />

serverData = JSON.parse(window.vuebnb_server_data); if ( ... ) { ... } else if ( ...<br />

) { ... } else { store.commit('addData', {route: to.name, data: serverData});<br />

serverData.saved.forEach(id => store.commit('toggleSaved', id)); next(); } });<br />

Let's also remove the placeholder listing IDs we added to saved in the previous<br />

chapter so the store is empty upon initialization.<br />

resources/assets/<strong>js</strong>/store.<strong>js</strong>: state: { saved: [], listing_summaries: [], listings: [],<br />

auth: false }<br />

With that done, we should find that the saved listings in the database now match<br />

those in the frontend if we check with <strong>Vue</strong> Devtools: $ php artisan tinker >>><br />

DB::table('users')->select('saved')->first(); # "saved": "[1,5,7,9]"

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

Saved successfully!

Ooh no, something went wrong!