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.

Refactoring<br />

Before we inject the initial state into the home page, let's do a small refactoring<br />

of the code including renaming some variables <strong>and</strong> restructuring some methods.<br />

This will ensure that the code semantics reflect the changing requirements <strong>and</strong><br />

keep our code readable <strong>and</strong> easy to underst<strong>and</strong>.<br />

Firstly, let's rename our template variable from $model to the more general $data.<br />

resources/views/app.blade.php: <br />

window.vuebnb_server_data = "{!! addslashes(<strong>js</strong>on_encode($data)) !!}"<br />

<br />

In our listing controller, we're now going to abstract any common logic from our<br />

listing route methods into a new helper method called get_listing. In this helper<br />

method, we will nest the Listing model inside a <strong>Laravel</strong> Collection under the<br />

listing key. Collection is an array-like wrapper for Eloquent models that offers a<br />

bunch of h<strong>and</strong>y methods that we'll be putting to use shortly. get_listing will<br />

include logic from the add_image_urls helper method, which can now safely be<br />

deleted.<br />

We'll also need to reflect the change to our template variable when we call the<br />

view method.<br />

app/Http/Controllers/ListingController.php: private function get_listing($listing) {<br />

$model = $listing->toArray(); for($i = 1; $i id . '/Image_' . $i . '.jpg'<br />

); } return collect(['listing' => $model]); } public function get_listing_api(Listing<br />

$listing) { $data = $this->get_listing($listing); return response()-><strong>js</strong>on($data); }<br />

public function get_listing_web(Listing $listing) { $data = $this-<br />

>get_listing($listing); return view('app', ['data' => $data]); }<br />

public function get_home_web()<br />

{<br />

return view('app', ['data' => []]);

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

Saved successfully!

Ooh no, something went wrong!