Reader small image

You're reading from  Laravel 5.x Cookbook

Product typeBook
Published inSep 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786462084
Edition1st Edition
Languages
Tools
Right arrow
Authors (2):
Terry Matula
Terry Matula
author image
Terry Matula

Terry Matula is a web developer and Laravel advocate based in Austin, TX. He's been a passionate computer enthusiast since he first played Oregon Trail on an Apple//e. He started programming in BASIC at a young age, making simple Scott Adams-like games on a Commodore Vic-20. Since then, he's worked as a developer using Flash/ActionScript, ASP.NET, PHP, and numerous PHP frameworks, with Laravel being his favorite by far. He blogs web development tips and tricks at his website http://terrymatula.com
Read more about Terry Matula

Alfred Nutile
Alfred Nutile
author image
Alfred Nutile

Alfred Nutile is an Enterprise Architect and Laravel lead based in Western Massachusetts. He's been working in the industry since the mid 90's. He started in PHP and MySQL back around that time and has worked with Ruby on Rails, Drupal, and Angular along the way. He introduced Laravel into an enterprise web stack, where he is currently contracted at, as Laravel proved itself as an amazing framework to build API's and Angular heavy application. You can read more about him and checkout his blog at http://www.alfrednutile.info/ or follow him on Twitter at https://twitter.com/alnutile Make sure to checkout the discount LaraCasts is offering those who buy the book! Get a coupon for 50% on your first bill. Make it a yearly subscription and save $43! Coupon Code: LaracastsLovesPackt https://laracasts.com/signup?plan=yearly&coupon=LaracastsLovesPackt.
Read more about Alfred Nutile

View More author details
Right arrow

Chapter 6. Adding Angular to Your App

In this chapter, we will cover the following topics:

  • Adding Angular search to our search page

  • Handling Angular and Ajax requests

  • Paginating our Angular results

  • Testing an Angular page with Behat

  • Creating a relationship with favorites

  • Building a favorites Ajax widget in Angular

  • Validating incoming input

  • Using the CORS protection

  • Using Elixir and Gulp to set up Angular

Introduction


I will show you how easy it is to get Angular into your application. I will also go over some workflow tips and tricks. When you are done with this chapter, you will have an easier time installing and plugging in Angular, as a widget into any part of your site!

Let's start by installing Angular 1.5. I will use this version over 2.x as it will be supported for quite some time, and the usage paradigm of it more closely follows what I am used to in Vue and other great JavaScript frameworks.

Getting ready

Any base installation of Laravel will work. In our case, we will be using the one from all the previous recipes.

How to do it...

  1. Let's install bower to help us install Angular:

    >sudo npm install -g bower
    
  2. Then, we need to initialize our app's bower file:

    >bower init
    

    Just answer default to all the questions.

  3. Let's install bower to help us get Angular:

    >bower install angular
    
  4. Then, by starting simple, I will copy over the file called bower_compontents/angular/angular.js into my...

Adding Angular search to our search page


In this section, we are going to convert the search to be Angular-based. What this means is that when the users will type in a word to search, they will then press Search and instead of reloading the page, we will do a request using Ajax and take the response of this request. I am not doing it because they type, due to API limitations at Marvel, but you could do this.

I need to also consider pagination later on and other odds and ends later on to this API.

Getting ready

It would be good to setup Angular as I did in the preceding recipe so that you are ready to start updating the MainController and your custom js file.

How to do it…

  1. First, we set up MainController to look like this:

    I will create the searchFor method, and then define it in my vm area.

    Tip

    Placing bindable members at the top makes it easy to read and helps you to instantly identify which members of the controller can be bound and used in the View—John Papa Guide

    Then, I add disableSearch so...

Handling Angular and Ajax requests


In this recipe, we will build both the backend sections in Laravel to take an Angular request, and then respond back to Angular. We will output the information into the Angular frontend.

First, I will update the initial controller that lays out the page so that we can share both the initial layout and the response results layout instead of having one driven by Laravel and another driven by Angular.

Getting ready

See the previous recipe on setting up the request. In this section, we will just continue from there.

How to do it…

The following are the steps for handling Angular and Ajax requests:

  1. I will install this https://github.com/laracasts/PHP-Vars-To-Js-Transformer library to begin with and use it in my Laravel controller:

    >composer require "Laracasts/utilities":"~2.0"
    
  2. Then, I follow all the installation steps seen on their GitHub page:

    1. Run vendor publish, so I can alter the config file:

      >php artisan vendor:publish
      
    2. Alter the config file config/javascript...

Paginating our Angular results


Now we have a ton of results, 730, as seen in this request:

Since we cannot show all 730 at once, and since the API gives us 20 at a time, let's paginate through their APIs.

Getting ready

Use a fresh Laravel installation and follow these steps.

How to do it…

  1. Install a library that helps with pagination and tons of other things:

    >npm install angular-ui-bootstrap --save
    
  2. Then, load the library into our public folder by copying it over to public/js and public/css. Later, we will optimize this part of the workflow:

  3. You will find all of these here:

  4. Then into the top of resources/views/layout.blade.php:

  5. And at the bottom of the same file:

  6. Now, in our public/js/app.js, we load the library:

  7. Now that we have loaded the libraries, let's use the Pagination buttons at the top and bottom of resources/views/home/_angular_search_results.blade.php:

  8. Let's take a closer look:

  9. The Angular Controller now needs to consider this new API query string and data points:

    I will go into the details...

Testing an Angular page with Behat


How about testing these Angular pages? In the previous recipes, I set up Behat and showed how to use this tool to not only test your site but also to help you write code. I will now show how easy it is to test it using Behat over other tools such as Protractor, since with Behat, we get the benefit of Gherkin-based tests that can both test the UI and do Integration-level tests.

Getting ready

In the previous recipes, I installed Behat. I will go over it again, so a base Laravel install should be enough.

How to do it...

  1. Install Behat using composer; your composer.json will look like this:

  2. Run composer update, or if you are impatient like me, run rm -rf vendor composer.lock, and then composer install

  3. Run Behat init to set things up:

    >vendor/bin/behat --init
    
  4. Make a behat.yml file at the root of your app like this:

  5. Run Behat again to set up these files (-s tells it what suite to use, and --init will set up the context class for us):

    >vendor/bin/behat --init ...

Creating a relationship with favorites


This is an Angular section, but I will take a moment to create a simple relationship, which we will later build a widget around. In this case, I am going to add a favorites table to the system and relate this to a user. It will hold the information I need to show a comic from Maravel.

Getting ready

A base installation of Laravel with the User model migrated is required here.

How to do it…

  1. Run this inside the virtual machine console:

    >php artisan make:migration create_favorites_table
    
  2. Open this file, and add the database/migrations/2016_05_16_220136_create_favorites_table.php fields:

  3. Then, make a model for this file:

    >php artisan make:model Favorite
    
  4. In this file, we can add a relationship back to the user:

  5. Then, open the user file called app/User.php to relate back to the favourites:

  6. Now, we are ready to build this UI.

How it works…

This is a fairly normal migration with a relationship with just a little extra. For one, notice the plural name of the favorites...

Building a favorites Ajax widget in Angular


What I will cover in this section is adding the ability for a user to click on a star next to the comic, and then it will be saved to the database, and added it as a Favorite via a widget on the page.

This is what they will see on the search results page:

When they click on the Favorites Tab, they see only their Favorites and can remove them:

This way you can see and remove Favorites. And since I am using a lot of the same layout, it should save me time.

Getting ready

See the previous recipe for setting up the model or just follow along.

How it works…

  1. Return favorites into the Home Page JavaScript:

    The getUserInfo method is here:

  2. Then, make a tab area on the home page to show this resources/views/home/index.blade.php data:

  3. Then, we update the template called resources/views/home/_search.blade.php:

    We also update resources/views/home/_favorites.blade.php:

  4. Now, when users click on Favorites, they will see them (but there are none):

  5. Now, add a button to the results...

Validating incoming input


The previous work did not cover validation. We could check for comic, and then check that the user is the owner. What I will do here is show how to use Form Request Validation to validate the incoming request.

Getting ready

If you have been following along, you have the app/Http/Controllers/FavoriteCreate.php controller in place, so we are going to add validation to it.

How to do it…

  1. Add toastr so that we can notify people as needed (https://github.com/Foxandxss/angular-toastr); you will see in the next layout that I had to move several files from the bower_components/angular-toastr to the public/js and public/css folders.

  2. I also install the Angular animate:

    >bower install angular-toastr#0.4.1 -S
    
  3. Add it to resources/views/layout.blade.php:

    Add it at the bottom of the file as well:

  4. Register it with the app called public/js/app.js:

  5. Then, add it to our handle error area:

  6. Let's make the form called request:

    >php artisan make:request FavoriteCreateRequest
    
  7. Then, add what...

Using the CORS protection


So far, even though the routes for this app are protected by the auth middleware, I am not dealing with CORS, because I am in the same domain as the login session and Angular has the benefits of sessions and XSRF.

You can see here that it is injecting it into the request for me as I use $http:

Figure 10 XSRF

So, if I went to another site in the same browser, the site cannot use the session from the site that I am coming from to make a request. In this case, if my request was using jQuery, for example, I would need to include this information. Here is an example using jQuery, so we can see a more manual approach to this.

Getting ready

For now, we will create a couple of routes with a basic jQuery Ajax request, and the POST request will be handled as well. I will cover this here, so just have a Laravel installation ready.

How to do it…

  1. We will make a new View that is really simple:

  2. Then, we make our Route file to serve these example routes:

  3. We make a test controller called...

Using Elixir and Gulp to set up Angular


After all the manual installation work at the start of this chapter, I want to step back and automate this with Elixir. I will use Gulp via Elixir to put my files in place for me and aggregate them as I work on them.

This means I will start to keep my assets in resources/assets" not "public and then aggregate them, as I edit them, to the correct areas.

To be clear, I am, by far, no Gulp expert. The system here just helped me to put in place a decent workflow, filling in some of the blanks I did not see in the Laravel docs.

Getting ready

If you did not follow the start of this chapter, you might not have all the files I am about to move into different places. If not, no big deal; you will still get a sense of how this all works.

How to do it...

  1. Move all CSS files into resources/css" and JavaScript "resources/js so that your folders look like this:

  2. Then, move all the CSS calls out of the layout, so it looks just like this:

  3. Then, I will do the same for the footer...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Laravel 5.x Cookbook
Published in: Sep 2016Publisher: PacktISBN-13: 9781786462084
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Terry Matula

Terry Matula is a web developer and Laravel advocate based in Austin, TX. He's been a passionate computer enthusiast since he first played Oregon Trail on an Apple//e. He started programming in BASIC at a young age, making simple Scott Adams-like games on a Commodore Vic-20. Since then, he's worked as a developer using Flash/ActionScript, ASP.NET, PHP, and numerous PHP frameworks, with Laravel being his favorite by far. He blogs web development tips and tricks at his website http://terrymatula.com
Read more about Terry Matula

author image
Alfred Nutile

Alfred Nutile is an Enterprise Architect and Laravel lead based in Western Massachusetts. He's been working in the industry since the mid 90's. He started in PHP and MySQL back around that time and has worked with Ruby on Rails, Drupal, and Angular along the way. He introduced Laravel into an enterprise web stack, where he is currently contracted at, as Laravel proved itself as an amazing framework to build API's and Angular heavy application. You can read more about him and checkout his blog at http://www.alfrednutile.info/ or follow him on Twitter at https://twitter.com/alnutile Make sure to checkout the discount LaraCasts is offering those who buy the book! Get a coupon for 50% on your first bill. Make it a yearly subscription and save $43! Coupon Code: LaracastsLovesPackt https://laracasts.com/signup?plan=yearly&coupon=LaracastsLovesPackt.
Read more about Alfred Nutile