Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

November 17 2017


Understanding Sets With JavaScript

Sets can be very powerful if you understand how to use them. A few applications of sets include solving counting problems where you may want to find the number of ways you can group elements together. 

Another application is problems that require you to find relationships between elements. The ECMAScript specification doesn’t include methods for operating on sets in this way. But it is possible to create your own. 

What follows is an overview of set theory with practical applications you can use to extend the capabilities of JavaScript and solve more complex problems.


  • Basics
  • Union
  • Intersection
  • Difference
  • Symmetric Difference
  • Complement
  • Review


A set is an unordered collection of elements that are all unique. For example, the list of all employees at your work is a set. Each employee would be an element in the set. In reality, these elements would be stored using an ID or Social Security number because these are values we can ensure will be unique. Note how the order of these elements is irrelevant to us because sorting IDs or Social Security numbers has no meaning.  

We call our set of employees the universal set because it contains all elements under consideration. Let’s imagine another set. This set is the list of employees at your company who work in the engineering department. This is a subset of our employee set because every element in the engineering set also exists in the employee set. Another subset is the list of employees who are freelance contractors. Here is how we would create these sets in JavaScript:

If you want to add another person to one of our sets, we would use the syntax set.add(value) and replace set with the name of our set and value with the value of the element being added. If we try to add an element that is already in the set, it will not be added. Example:

This will print Set { 'Alberta', 'Dr. Gero', 'Trunks', 'Bulma', 'Gohan' }.

Right now, you may be thinking so what? What can I do with this information? Next we will see how we can operate on sets to help us solve some common problems.


What if we want to find all the employees in our company who are freelancers or who work in the engineering department? We would need to combine the two sets, and then remove any duplicate names. This is called the union. 

The union of two sets is the set that contains elements from either set or both sets. Notice how elements in our engineering set are also in the freelancers set. Here is one way you can find the union of both sets:

The ... operator turns our set into an array, and after combining the two arrays, the Set constructor removes the duplicate elements. The union of the two sets will be Set {'Alberta', 'Dr. Gero', 'Trunks', 'Bulma', 'Gohan', 'Piccolo', 'Vegeta', 'Goku' }.


What is the union of the sets [1, 3, 5, 7, 9] and [2, 3, 4, 6]?


Suppose we want to find all the employees who are in the engineering department and are freelancers. This is the intersection of the sets. The intersection of two sets is the set containing elements in both sets. 

To reproduce this, we can search through one set and check if each element is in the other set. To check if an element is in a set, we use the has method. Example:

This would return true. Using the has method, we can filter our engineering set for items that are also in the freelancers set.

The intersection of engineering and freelancers is Set { 'Trunks', 'Gohan' }.


What is the intersection of the sets [1, 3, 5, 7, 9] and [2, 3, 4, 6]?


Let’s consider the scenario where we want to find the engineers who are not freelancers. This is the difference. The difference of two sets is the set containing elements that are in the first set, but not in the second set. 

For us, that means we will start with our engineering set, and then remove any elements that are also in the freelancers set. Example:

The difference of the engineering set and the freelancers set is Set { 'Alberta', 'Dr. Gero', 'Bulma' }. If we want to get the list of people who are freelancers and not engineers, we start with the freelancers set and remove the elements that appear in the engineers set. Example:

This gives us a different result. The difference of the freelancers set and the engineering set is Set { 'Piccolo', 'Vegeta', 'Goku' }.


Find the difference of [1, 3, 5, 7, 9] and [2, 3, 4, 6].

Find the difference of [2, 3, 4, 6] and [1, 3, 5, 7, 9].

Symmetric Difference

Now, we would like to find who in the company is either an engineer or a freelancer, but not both. This is the symmetric difference. The symmetric difference of two sets is the set containing elements from either set, but not both sets. 

One approach we could use is to find the union of the two sets (everyone who is an engineer, freelancer, or both) and subtract the intersection (everyone who is both an engineer and a freelancer). Combining the techniques we used previously, we can get the symmetric difference with the following code:

The symmetric difference of our engineering set and our freelancers set is Set { 'Alberta', 'Dr. Gero', 'Bulma', 'Piccolo', 'Vegeta', 'Goku' }.


Find the symmetric difference of [1, 3, 5, 7, 9] and [2, 3, 4, 6].


If we have our set of employees and a set of engineers, how could we find the set of all people who are not engineers? One thing we could do is subtract the engineers set from the employees set. This set is the complement to our engineers set in relation to our employees set. Example:

The complement to the engineering set in relation to our employees set is Set { 'Goku', 'Piccolo', 'Vegeta' }.


Given the universal set [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10], find the complement to set [2, 4, 6, 8, 10].


Sets come in handy when you need to compare different lists, combine lists, or find unique elements in a list. The next time you have a problem where you need to analyze data in this way, consider using one of the set operations mentioned above. Here is a list of the key terms that were discussed:

  • Set: A collection of unique, unordered elements.
  • Universal set: All possible elements of a set.
  • Subset: A smaller set within a set.
  • Union of sets A and B: The set that contains elements in either A, B or both.
  • Intersection of sets A and B: The set containing elements from both A and B.
  • Difference of sets A and B: The set containing elements in A but not in B.
  • Symmetric difference of sets A and B: The set containing elements in either A or B, but not both.
  • Complement of set A: The elements in the universal set that are not in A.

As usual, remember if you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato Market.

November 16 2017


How to Index and Query Data With Haystack and Elasticsearch in Python


Haystack is a Python library that provides modular search for Django. It features an API that provides support for different search back ends such as Elasticsearch, Whoosh, Xapian, and Solr.


Elasticsearch is a popular Lucene search engine capable of full-text search, and it's developed in Java.

Google search uses the same approach of indexing their data, and that's why it's very easy to retrieve any information with just a few keywords, as shown below.

Elastic Search and Google

Install Django Haystack and Elasticsearch

The first step is to get Elasticsearch up and running locally on your machine. Elasticsearch requires Java, so you need to have Java installed on your machine.

We are going to follow the instructions from the Elasticsearch site.

Download the Elasticsearch 1.4.5 tar as follows:

Extract it as follows:

It will then create a batch of files and folders in your current directory. We then go into the bin directory as follows:

Start Elasticsearch as follows.

To confirm if it has installed successfully, go to, and you should see something like this.

Ensure you also have haystack installed.

Let's create our Django project. Our project will be able to index all the customers in a bank, making it easy to search and retrieve data using just a few search terms.

This command creates files that provide configurations for Django projects.

Let's create an app for customers. Configurations

In order to use Elasticsearch to index our searchable content, we’ll need to define a back-end setting for haystack in our project's file. We are going to use Elasticsearch as our back end.

HAYSTACK_CONNECTIONS is a required setting and should look like this:

Within the, we are also going to add haystack and customers to the list of installed apps.

Create Models

Let's create a model for Customers. In customers/, add the following code.

Register your Customer model in like this:

Create Database and Super User

Apply your migrations and create an admin account.

Run your server and navigate to http://localhost:8000/admin/. You should now be able to see your Customer model there. Go ahead and add new customers in the admin.

Indexing Data

To index our models, we begin by creating a SearchIndex. SearchIndex objects determine what data should be placed in the search index. Each type of model must have a unique searchIndex.

SearchIndex objects are the way haystack determines what data should be placed in the search index and handles the flow of data in. To build a SearchIndex, we are going to inherit from the indexes.SearchIndex and indexes.Indexable, define the fields we want to store our data with, and define a get_model method.

Let's create the CustomerIndex to correspond to our Customer modeling. Create a file in the customers app directory, and add the following code.

The EdgeNgramField is a field in the haystack SearchIndex that prevents incorrect matches when parts of two different words are mashed together.

It allows us to use the autocomplete feature to conduct queries. We will use autocomplete when we start querying our data.

document=True indicates the primary field for searching within. Additionally, the  use_template=True in the text field allows us to use a data template to build the document that will be indexed.

Let's create the template inside our customers template directory. Inside   search/indexes/customers/customers_text.txt, add the following:

Reindex Data

Now that our data is in the database, it's time to put it in our search index. To do this, simply run ./ rebuild_index. You’ll get totals of how many models were processed and placed in the index.

Alternatively, you can use RealtimeSignalProcessor, which automatically handles updates/deletes for you. To use it, add the following in the file.

Querying Data

We are going to use a search template and the Haystack API to query data.

Search Template

Add the haystack urls to your URLconf.

Let's create our search template. In templates/search.html, add the following code.

The page.object_list is a list of SearchResult objects that allows us to get the individual model objects, for example, result.first_name.

Your complete project structure should look something like this:

The project directory structure

Now run server, go to, and do a search as shown below.

Running a search on a local server

A search of Albert will give results of all customers with the name Albert. If no customer has the name Albert, then the query will give empty results. Feel free to play around with your own data.

Haystack API

Haystack has a SearchQuerySet class that is designed to make it easy and consistent to perform searches and iterate results. Much of the SearchQuerySet API is familiar with Django’s ORM QuerySet.

In customers/, add the following code:

autocomplete is a shortcut method to perform an autocomplete search. It must be run against fields that are either EdgeNgramField or NgramField.

In the above Queryset, we are using the contains method to filter our search to retrieve only the results that contain our defined characters. For example, Al will only retrieve the details of the customers which contain Al. Note that the results will only come from fields that have been defined in the customer_text.txt file.

The results of a query

Apart from the contains Field Lookup, there are other fields available for performing queries, including:

  • content
  • contains
  • exact
  • gt
  • gte
  • lt
  • lte
  • in
  • startswith
  • endswith
  • range
  • fuzzy


A huge amount of data is produced at any given moment in social media, health, shopping, and other sectors. Much of this data is unstructured and scattered. Elasticsearch can be used to process and analyze this data into a form that can be understood and consumed.

Elasticsearch has also been used extensively for content search, data analysis, and queries. For more information, visit the Haystack and Elasticsearch sites.

November 15 2017


How to Upload Images to Firebase from an Android App

Firebase is a mobile and web application development platform, and Firebase Storage provides secure file uploads and downloads for Firebase apps. In this post, you'll build an Android application with the ability to upload images to Firebase Storage.

Firebase Setup

If you don't have a Firebase account yet, you can create one at the Firebase home page.

Once your account is set up, go to your Firebase console, and click the Add Project button to add a new project.

Firebase home page

Enter your project details and click the Create Project button when done. On the next page, click on the link to Add Firebase to your Android app.

Create project options

Enter your application package name. My application package is Note that the package name is namespaced with a unique string that identifies you or your company. An easy way to find this is to open your MainActivity file and copy the package name from the top.

Add Firebase to your Android app

When done, click on Register App. On the next page, you will be given a google-services.json to download to your computer. Copy and paste that file into the app folder of your application. (The path should be something like TutsplusUpload/app.)

Set Firebase Permissions

To allow your app access to Firebase Storage, you need to set up permissions in the Firebase console. From your console, click on Storage, and then click on Rules.

Firebase Storage permissions rules

Paste the rule below and publish. 

This will allow read and write access to your Firebase storage.

Create the Application

Open up Android Studio, and create a new project. You can call your project anything you want. I called mine TutsplusUpload.

Before you proceed, you'll need to add a couple of dependencies. On the left panel of your Android Studio, click on Gradle Scripts.

buildgradle file

Open build.gradle (Project: TutsplusUpload), and add this line of code in the dependencies block.

Next, open build.gradle (Module: app) to add the dependencies for Firebase. These go in the dependencies block also. 

Finally, outside the dependencies block, add the plugin for Google Services.

Save when done, and it should sync.

Set Up the MainActivity Layout

The application will need one activity layout. Two buttons will be needed—one to select an image from your device, and the other to upload the selected image. After selecting the image you want to upload, the image will be displayed in the layout. In other words, the image will not be set from the layout but from the activity.

In your MainActivity layout, you will use two layouts—nesting the linear layout inside the relative layout. Start by adding the code for your relative layout.

The RelativeLayout takes up the whole space provided by the device. The LinearLayout will live inside the RelativeLayout, and will have the two buttons. The buttons should be placed side by side, thus the orientation to be used for the LinearLayout will be horizontal.

Here is the code for the linear layout.

From the above code, you can see that both buttons have ids assigned. The ids will be used to target the button from the main activity such that when the button gets clicked, an interaction is initiated. You will see that soon.

Below the LinearLayout, add the code for the ImageView.

You can also see that the ImageView has an id; you will use this to populate the layout of the selected image. This will be done in the main activity.

Get MainActivity Up

Navigate to your MainActivity, and start by declaring fields. These fields will be used to initialize your views (the buttons and ImageView), as well as the URI indicating where the image will be picked from. Add this to your main activity, above the onCreate method.

PICK_IMAGE_REQUEST is the request code defined as an instance variable.

Now you can initialize your views like so:

In the above code, you are creating new instances of Button and ImageView. The instances point to the buttons you created in your layout.

You have to set a listener that listens for interactions on the buttons. When an interaction happens, you want to call a method that triggers either the selection of an image from the gallery or the uploading of the selected image to Firebase.

Underneath the initialized views, set the listener for both buttons. The listener looks like this.

This should be in the onCreate() method. As I mentioned above, both buttons call a different method. The Choose button calls the chooseImage() method, while the Upload button calls the uploadImage() method. Let's add those methods. Both methods should be implemented outside the onCreate() method.

Let's start with the method to choose an image. Here is how it should look:

When this method is called, a new Intent instance is created. The intent type is set to image, and its action is set to get some content. The intent creates an image chooser dialog that allows the user to browse through the device gallery to select the image. startActivityForResult is used to receive the result, which is the selected image. To display this image, you'll make use of a method called onActivityResult.

onActivityResult receives a request code, result code, and the data. In this method, you will check to see if the request code equals PICK_IMAGE_REQUEST, with the result code equal to RESULT_OK and the data available. If all this is true, you want to display the selected image in the ImageView.

Below the chooseImage() method, add the following code.

Uploading the File to Firebase

Now we can implement the method for uploading the image to Firebase. First, declare the fields needed for Firebase. Do this below the other fields you declared for your class.

storage will be used to create a FirebaseStorage instance, while storageReference will point to the uploaded file. Inside your onCreate() method, add the code to do that—create a FirebaseStorage instance and get the storage reference. References can be seen as pointers to a file in the cloud.

Here is what the uploadImage() method should look like.

When the uploadImage() method is called, a new instance of ProgressDialog is initialized. A text notice showing the user that the image is being uploaded gets displayed. Then a reference to the uploaded image, storageReference.child(), is used to access the uploaded file in the images folder. This folder gets created automatically when the image is uploaded. Listeners are also added, with toast messages. These messages get displayed depending on the state of the upload.

Set Permission in the App

Finally, you need to request permission that your application will make use of. Without this, users of your application will not be able to browse their device gallery and connect to the internet with your application. Doing this is easy—simply paste the following in your AndroidManifest file. Paste it just above the application element tag.

This requests for permission to use the internet and read external storage.

Testing the App

Now go ahead and run your application! You should be able to select an image and successfully upload it to Firebase. To confirm the image uploaded, go back to your console and check in the Files part of your storage.

The finished app


Firebase provides developers with lots of benefits, and file upload with storage is one of them. Uploading images from your Android application requires you to work with Activities and Intents. By following along with this tutorial, your understanding of Activities and Intents has deepened. I hope you enjoyed it!

Check out some of our other posts for more background about Activities and Intents, or take a look at some of our other tutorials on using Firebase with Android!

  • Android SDK
    What Are Android Intents?
    Chinedu Izuchukwu
  • Android SDK
    What Is the Android Activity Lifecycle?
    Chinedu Izuchukwu
  • Android SDK
    Firebase for Android: File Storage
    Paul Trebilcox-Ruiz
  • Android SDK
    How to Create an Android Chat App Using Firebase
    Ashraff Hathibelagal


New eBooks Available for Subscribers

Do you want to learn more about programming for the Internet of Things? How about mastering object-oriented programming or game development with Swift? Our latest batch of eBooks will teach you all you need to know about these topics and more. What's more, they're all completely free for Envato Elements subscribers to download.

eBooks available for Tuts subscribers

Our Latest Selection of eBooks

This month we’ve made eight new eBooks available for Envato Elements and Tuts+ subscribers to download. Here’s a summary of those books and what you can learn from them.

  • Swift 3 Object-Oriented Programming

    Swift 3 Object-Oriented Programming

    Want to program iOS apps? This book introduces you to the object-oriented paradigm and its implementation in the Swift 3 programming language to help you understand how real-world objects can become part of fundamental reusable elements in the code. 

    You will organize data in blueprints that generate instances. You’ll work with examples so you understand how to encapsulate and hide data by working with properties and access control. Then, you’ll get to grips with complex scenarios where you use instances that belong to more than one blueprint. You’ll discover the power of contract programming and parametric polymorphism. You’ll combine generic code with inheritance and multiple inheritance. Later, you’ll see how to combine functional programming with object-oriented programming and find out how to refactor your existing code for easy maintenance.

  • Swift 3 Game Development

    Swift 3 Game Development

    Swift is the perfect choice for game development. Developers are intrigued by Swift 3.0 and want to make use of new features to develop their best games yet. Packed with best practices and easy-to-use examples, this book leads you step by step through the development of your first Swift game.

    This book starts by introducing SpriteKit and Swift's new features that can be used for game development. After setting up your first Swift project, you will build your first custom class, learn how to draw and animate your game, and add physics simulations.

    Then, you will add the player character, scenes, backgrounds, menus, leaderboards, and much more. By the end of this book, you will be able to create your own iOS games using Swift and SpriteKit.

  • Learning Functional Data Structures and Algorithms

    Learning Functional Data Structures and Algorithms

    With the advent of functional programming and with powerful functional languages such as Scala, Clojure and Elixir becoming part of important enterprise applications, functional data structures have gained an important place in the developer toolkit. But how do we express traditional algorithms in functional setting? Won’t we end up copying too much? Do we trade performance for versioned data structures?

    This book attempts to answer these questions by looking at functional implementations of traditional algorithms. By the end of the book, you'll have a solid understanding of functional programming and will be able to write efficient functional data structures and algorithms for your applications.

  • Angular Test-Driven Development

    Angular Test-Driven Development

    This is a complete guide that shows you testing techniques with Karma that will help you perform unit testing and end-to-end testing with Protractor. It will show you how to optimize your Angular development process using TDD techniques and ensure your final project is free of bugs. All examples in this book are based on Angular v2 and are compatible with Angular v4.

    You'll start by reviewing the TDD life cycle, TDD in the context of JavaScript, and various JavaScript test tools and frameworks. Then you'll learn to test for multiple classes, partial views, location references, CSS, and the HTML element. Amongst other things, you'll also configure a Karma file to automate the testing and tackle elements of Angular (components, services, classes, and broadcasting) using TDD.

  • Angular Services

    Angular Services

    A primary concern with modern-day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular leverages its services to create such state-of-the-art dynamic applications.

    This book will help you create and design customized services, integrate them into your applications, import third-party plugins, and make your apps perform better and faster. This book is up to date for the 2.4 release and is compatible with the 4.0 release as well, and it does not have any code based on the beta or release candidates.

  • Internet of Things Programming With JavaScript

    Internet of Things Programming With JavaScript

    The Internet of Things (IoT) is an entirely new platform for developers and engineers, but you can use the familiar JavaScript programming language. This book will teach you how to interact with endpoint devices by developing web services in JavaScript and also set up an interface to control all connected devices.

    The book begins with setting up a centralized web server that serves as a hub for all connected devices. It then progresses further towards building web services to facilitate high-level communication between connected devices. Using Arduino and Raspberry Pi Zero as endpoint devices, the book will show you how devices can communicate with each other, perform a wide range of tasks, and also be controlled from a centralized location using JavaScript. You'll end by creating a hybrid app to control the devices that can be run from a browser or installed on a smartphone.

  • Go Design Patterns

    Go Design Patterns

    Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently address common problems faced during developing applications.

    Go Design Patterns provides you with a reference point to software design patterns and CSP concurrency design patterns to help them build applications in a more idiomatic, robust, and convenient way in Go.

    The book starts with a brief introduction to Go programming essentials and design patterns. You will then learn how to apply the 23 Gang of Four (GoF) design patterns in Go and also learn about CSP concurrency patterns, the "killer feature" in Go that has helped Google develop software to maintain thousands of servers.

  • Functional PHP

    Functional PHP

    A functional approach encourages code reuse, greatly simplifies testing, and results in code that is concise and easy to understand. This book will demonstrate how PHP can also be used as a functional language, letting you learn about various function techniques to write maintainable and readable code.

    After a quick introduction to functional programming, you will dive right in with code examples so you can get the most of what you’ve learned. Through the tips and best practices in this book, you’ll be able to do more with less code and reduce bugs in your applications. Not only will you be able to boost your performance, but you will also find out how to eliminate common loop problems. By the end of the book, you will know a wide variety of new techniques that you can use on any new or legacy codebase.

Start Reading With a Combined Subscription

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to these eBooks, but also to our growing library of over 1,000 video courses on Envato Tuts+.

Plus you now get unlimited downloads from the huge Envato Elements library of 400,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.


Gates and Policies in Laravel

Today, we're going to discuss the authorization system of the Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After an introduction to gates and policies, I'll demonstrate the concepts by implementing a custom example.

I assume that you're already aware of the built-in Laravel authentication system as that's something essential in order to understand the concept of authorization. Obviously, the authorization system works in conjunction with the authentication system in order to identify the legitimate user session.

If you're not aware of the Laravel authentication system, I would highly recommend going through the official documentation, which provides you with hands-on insight into the subject.

Laravel's Approach to Authorization

By now, you should already know that the Laravel authorization system comes in two flavors—gates and policies. Although it may sound like a complicated affair, I would say it's pretty easy to implement it once you get the hang of it!

Gates allow you to define an authorization rule using a simple closure-based approach. In other words, when you want to authorize an action that's not related to any specific model, the gate is the perfect place to implement that logic.

Let's have a quick look at what gate-based authorization looks like:

The above snippet defines the authorization rule update-post that you could call from anywhere in your application.

On the other hand, you should use policies when you want to group the authorization logic of any model. For example, let's say you have a Post model in your application, and you want to authorize the CRUD actions of that model. In that case, it's the policy that you need to implement.

As you can see, it's a pretty simple policy class that defines the authorization for the CRUD actions of the Post model.

So that was an introduction to gates and policies in Laravel. From the next section onwards, we'll go through a practical demonstration of each element.


In this section, we'll see a real-world example to understand the concept of gates.

More often than not, you end up looking at the Laravel service provider when you need to register a component or a service. Following that convention, let's go ahead and define our custom gate in the app/Providers/AuthServiceProvider.php as shown in the following snippet.

In the boot method, we've defined our custom gate:

While defining a gate, it takes a closure that returns either TRUE or FALSE based on the authorization logic that's defined in the gate definition. Apart from the closure function, there are other ways you could define gates.

For example, the following gate definition calls the controller action instead of the closure function.

Now, let's go ahead and add a custom route so that we can go through a demonstration of how gate-based authorization works. In the routes file routes/web.php, let's add the following route.

Let's create an associated controller file app/Http/Controllers/PostController.php as well.

In most cases, you'll end up using either the allows or denies method of the Gate facade to authorize a certain action. In our example above, we've used the allows method to check if the current user is able to perform the update-post action.

Users with sharp eyes would have noticed that we've only passed the second argument $post to the closure. The first argument, the current logged-in user, is automatically injected by the Gate facade.

So that's how you're supposed to use gates to authorize actions in your Laravel application. The next section is all about how to use policies, should you wish to implement authorization for your models.


As we discussed earlier, when you want to logically group your authorization actions for any particular model or resource, it's the policy you're looking for.

In this section, we'll create a policy for the Post model that will be used to authorize all the CRUD actions. I assume that you've already implemented the Post model in your application; otherwise, something similar will do.

The Laravel artisan command is your best friend when it comes to creating stubbed code. You can use the following artisan command to create a policy for the Post model.

As you can see, we've supplied the --model=Post argument so that it creates all the CRUD methods. In the absence of that, it'll create a blank Policy class. You can locate the newly created Policy class at app/Policies/PostPolicy.php.

Let's replace it with the following code.

To be able to use our Policy class, we need to register it using the Laravel service provider as shown in the following snippet.

We've added the mapping of our Policy in the $policies property. It tells Laravel to call the corresponding policy method to authorize the CRUD action.

You also need to register the policies using the registerPolicies method, as we've done in the boot method.

Moving further, let's create a couple of custom routes in the routes/web.php file so that we can test our Policy methods there.

Finally, let's create an associated controller at app/Http/Controllers/PostController.php.

There are different ways you could authorize your actions using Policies. In our example above, we’ve used the User model to authorize our Post model actions.

The User model provides two useful methods for authorization purposes—can and cant. The can method is used to check if the current user is able to execute a certain action. And the counterpart of the can method, the cant method, is used to determine the inability of the action execution.

Let’s grab the snippet of the view method from the controller to see what exactly it does.

Firstly, we load the currently logged-in user, which gives us the object of the User model. Next, we load an example post using the Post model.

Moving ahead, we’ve used the can method of the User model to authorize the view action of the Post model. The first argument of the can method is the action name that you want to authorize, and the second argument is the model object that you want to get authorized against.

That was a demonstration of how to use the User model to authorize the actions using policies. Alternatively, you could use the Controller Helper as well, if you’re in the controller while authorizing a certain action.

As you can see, you don’t need to load the User model if you use the Controller Helper.

So that was the concept of policies at your disposal, and it’s really handy while authorizing a model or a resource as it allows you to group the authorization logic in one place.

Just make sure that you don’t use gates and policies altogether for the same actions of the Model, otherwise it’ll create issues. That’s it from my side for today, and I’ll call it a day!


Today, it was Laravel authorization that took the center stage in my article. At the beginning of the article, I introduced the main elements of Laravel authorization, gates and policies.

Following that, we went through creating our custom gate and policy to see how it works in the real world. I hope you’ve enjoyed the article and learned something useful in the context of Laravel.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

As always, I would love to hear from you in the form of comments using the feed below!


Envato Elements Now Includes WordPress Themes & Plugins!

If you work with WordPress, you're in luck—WordPress themes and plugins are now included in an annual Envato Elements subscription. And what's more, you can lock in a special introductory rate for a limited time. Read on for more details.

Adios theme on Envato Elements

What's Included

Envato Elements already gives you unlimited downloads from a massive library of 400,000+ photos, graphics, templates, and other creative assets. Plus it gives you free access to more than 1,000 courses and 240 eBooks here on Envato Tuts+.

From today, you'll still get all of that plus a curated collection of beautiful, premium WordPress themes and plugins. 

As with everything else on Envato Elements, this is an "all you can eat" deal. You can download as many themes and plugins as you want, with no limits or credits to keep track of. And there's a simple licensing system so that you know you're covered for all of your projects.

Right now, there are over 190 top themes and 130 plugins available to choose from, and you can expect that number to grow as more authors join the platform and existing authors upload more items. 

WordPress Themes

There's a wide range of premium themes on offer, whether you're looking for a multipurpose theme suitable for a corporate audience or something more creative that would work for a blog or portfolio site. There are even niche themes for real estate sites, wedding sites and more—and of course, you can find e-commerce themes to help you make sales from your site.

Focuson theme on Envato Elements

WordPress Plugins

A well-designed theme is a great start, of course, but if you're working with WordPress you'll also need access to premium plugins to add the features and functionality you want.

Envato Elements has you covered here too, with a selection of powerful plugins to help you create booking and scheduling systems, contact forms, responsive menus, social media feeds, and more.

FlyFly WordPress plugin on Envato Elements

What It Costs

It's important to understand that WordPress themes and plugins are only available with an annual subscription, not a monthly one. Usually, an Envato Elements subscription costs $29 a month, so the annual subscription will be $348 a year ($29 x 12).

However, for a limited time, you can save $120 on your subscription and sign up for just $228 (the equivalent of $19 a month). Remember, for that price you get not only the WordPress themes and plugins but also thousands of photos, fonts, graphics, templates and more. It's a pretty special deal.

So head over to Envato Elements to see what's on offer, and if you like what you see, sign up for an annual subscription to start making unlimited downloads. Don't spend too long thinking about it, though, because this introductory deal won't last forever!

November 14 2017


How to Create Simple Button Fades With CSS

In this video from my course on Practical Web Animation, you'll learn how to create a simple hover effect using CSS. We'll be making our navigation buttons more interesting by animating the background and text colors on hover. You'll also learn some neat CSS tricks for properly centering a menu on the page.

How to Create Simple Button Fades


Fork the Pen and Make Style Changes

The first thing you need to do is create your own version of the starting pen on CodePen, which contains all the code you need to get started.

So once you open that up, go ahead and click on the Fork button to create a new copy of it, and then you can start making changes in your new copy. 

First, I want to reduce the space between the buttons. You can do that by setting margin-right to a value of 4px. And you'll see they're a lot closer together. 

Center the Menu

Next, we want to center this navigation on the page. By default, an unordered list is a block-level element, and the easiest way to center a block-level element is using margin: 0 auto;

Our unordered list has a class of .main-nav, so go into that rule and add margin: 0 auto;

At first, that won't work, because since it is a block-level element, by default it takes up the full width of the browser or of its container.

So in order to center it, we first need to give it a width. And I want its width to be determined by the number of items in the menu and the amount of space that those items take up. 

We have five buttons, each with a width of 140 px. And then we have a margin-right on each of those list items of 4 px. So the total width is 5 x 140 = 700, plus the spacing in between, which is 4 x 4 = 16. So our total width of this unordered list is 716 px.

But if we add width: 716px; in the .main-nav class, it doesn't work. You'll see that it does center things, but the "CONTACT US" button has been nudged down to the next line. 

Menu broken onto next line

That's because the "CONTACT US" button also has a margin-right of 4 px. So it's that fifth margin-right that makes it wider than 716 px.

We could fix it by setting our width to 720, but then it's not perfectly centered because we have four extra pixels of margin on the right. So a better option is to simply get rid of the margin-right for the last list item.

We can do that by creating a new rule:

When we do that, everything works fine, and we can go back down to 716 px for the width now, and we see that our "CONTACT US" button is not breaking down to the next line.

Menu properly centered

One more thing we should do is space the menu down a little bit so it's not so close to the top of the browser window. So instead of margin: 0 auto;, we could do margin: 20px auto. That will give it a margin of 20 pixels on the top and on the bottom. And then the auto, obviously, would center it horizontally. 

Create the Hover Effect

So now let's create our hover effect. Our anchor tag right now doesn't have a background color applied to it at all. So let's grab the background color from the list item, cut it, and then move it down to our anchor tag itself. So now our anchor tags have that background color.

Then we'll create a new rule for the hover effect for those anchor tags:

Now, when we hover over the buttons, the background disappears. 

Background disappearing on hover

In order to make this a little more eye-catching, we're going to add a subtle fade. When we're going to fade an item, we first need to determine which rule we need to apply this transition property to. We're not going to apply it to the hover rule; we're going to apply it to the original rule for the anchor tag inside that main nav.

So for that original rule, we're going to add transition: all .5s;. This means that any property we decide to animate will go ahead and animate, and it will last half a second. So now when we hover over each of these buttons, we have a nice subtle fade out.

Make Two Things Fade at the Same Time

Let's tweak this a little bit so that we're fading two different things at the same time. So let's save our work in CodePen and then fork a new version. 

Then take away the background color altogether and put a border around the buttons. So for our original anchor tag rule, we're going to get rid of our background color, and instead we're going to have a border. So add border: 1px solid white;

You'll notice that everything breaks again, and the "CONTACT US" button jumps down to the next line. 

Buttons spacing broken to next line

That's because whenever you add a border to an item that already has a defined width, that border is going to make that item larger. So our width is set to 140 px, but then we have one pixel of border on the left and one pixel of border on the right, making the full width 142 px. 

That's the default behavior, but there is a property called box-sizing that allows us to change that default behavior. If we change box-sizing to border-box, then the final width of our item will be whatever we define for it. So if we define a width of 140 px and then add borders to it, those borders will show up inside the item, and the final width of the item will still be 140 px.

So you can go up to the top and add a new line:

And when we do that, you'll see it automatically gets fixed.

Borders with spacing fixed

Now when we hover over these anchor tags, I want the background color to change to white, and I want the text to change to blue.

So instead of setting our background color to the color of our body background, we're going to set it to a value of white (#fff). So now when we hover over a button, the background color goes to white. And now we just want to change the color of the text to #349, which is the same blue as our background. 

So now when we hover over those, it just inverts itself. The text, which was white, is now the same blue as the background. And the background, which was blue, has changed to white.

Final button fade

Watch the Full Course

In the full course, Practical Web Animation, I will show you practical ways to create animations for buttons, pricing tables, and other web elements, using concise CSS and jQuery to do so.

You can take this course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 300,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.


WordPress Live: Up and Running With WooCommerce

WooCommerce is the most popular eCommerce platform on the web and the most popular way of bringing eCommerce to WordPress. If you're creating an online store, you might be surprised at how easy it is to get up and running with WooCommerce!

In this free live stream course, Rachel McCollin will show you how to set up the WooCommerce plugin for WordPress. Follow along live on YouTube as she installs and configures a WooCommerce store.

Watch the course live to ask questions as you follow along!

If you can't make it to the live stream, you always can watch the recorded course later on Envato Tuts+.


Java 8 for Android Development: Stream API and Date & Time Libraries

In this three-part series, we’ve been exploring all the major Java 8 features that you can start using in your Android projects today.

In Cleaner Code With Lambda Expressions, we focused on cutting boilerplate from your projects using lambda expressions, and then in Default and Static Methods, we saw how to make these lambda expressions more concise by combining them with method references. We also covered Repeating Annotations and how to declare non-abstract methods in your interfaces using default and static interface methods.

In this final post, we’re going to look at type annotations, functional interfaces, and how to take a more functional approach to data processing with Java 8’s new Stream API.

I’ll also show you how to access some additional Java 8 features that aren’t currently supported by the Android platform, using the Joda-Time and ThreeTenABP libraries.

Type Annotations

Annotations help you write code that’s more robust and less error-prone, by informing code inspection tools such as Lint about the errors they should be looking out for. These inspection tools will then warn you if a piece of code doesn’t conform to the rules laid out by these annotations.

Annotations aren’t a new feature (in fact, they date back to Java 5.0), but in previous versions of Java it was only possible to apply annotations to declarations.

With the release of Java 8, you can now use annotations anywhere you've used a type, including method receivers; class instance creation expressions; the implementation of interfaces; generics and arrays; the specification of throws and implements clauses; and type casting.

Frustratingly, although Java 8 does make it possible to use annotations in more locations than ever before, it doesn’t provide any annotations that are specific to types.

Android’s Annotations Support Library provides access to some additional annotations, such as @Nullable, @NonNull, and annotations for validating resource types such as  @DrawableRes, @DimenRes, @ColorRes, and @StringRes. However, you may also want to use a third-party static analysis tool, such as the Checker Framework, which was co-developed with the JSR 308 specification (the Annotations on Java Types specification). This framework provides its own set of annotations that can be applied to types, plus a number of "checkers" (annotation processors) that hook into the compilation process and perform specific “checks” for each type annotation that’s included in the Checker Framework.

Since Type Annotations don’t affect runtime operation, you can use Java 8’s Type Annotations in your projects while remaining backwards compatible with earlier versions of Java.

Stream API

The Stream API offers an alternative, “pipes-and-filters” approach to collections processing.

Prior to Java 8, you manipulated collections manually, typically by iterating over the collection and operating on each element in turn. This explicit looping required a lot of boilerplate, plus it’s difficult to grasp the for-loop structure until you reach the body of the loop.

The Stream API gives you a way of processing data more efficiently, by performing a single run over that data—regardless of the amount of data you’re processing, or whether you're performing multiple computations.

In Java 8, every class that implements java.util.Collection has a stream method that can convert its instances into Stream objects. For example, if you have an Array:

Then you can convert it into a Stream with the following:

The Stream API processes data by carrying values from a source, through a series of computational steps, known as a stream pipeline. A stream pipeline is composed of the following:

  • A source, such as a Collection, array, or generator function.
  • Zero or more intermediate “lazy” operations. Intermediate operations don’t start processing elements until you invoke a terminal operation—which is why they’re considered lazy. For example, calling Stream.filter() on a data source merely sets up the stream pipeline; no filtering actually occurs until you call the terminal operation. This makes it possible to string multiple operations together, and then perform all of these computations in a single pass of the data. Intermediate operations produce a new stream (for example, filter will produce a stream containing the filtered elements) without modifying the data source, so you’re free to use the original data elsewhere in your project, or create multiple streams from the same source.
  • A terminal operation, such as Stream.forEach. When you invoke the terminal operation, all of your intermediate operations will run and produce a new stream. A stream isn’t capable of storing elements, so as soon as you invoke a terminal operation, that stream is considered “consumed” and is no longer usable. If you do want to revisit the elements of a stream, then you’ll need to generate a new stream from the original data source.

Creating a Stream

There are various ways of obtaining a stream from a data source, including:

  • Stream.of() Creates a stream from individual values:

  • IntStream.range() Creates a stream from a range of numbers:

  • Stream.iterate() Creates a stream by repeatedly applying an operator to each element. For example, here we’re creating a stream where each element increases in value by one:

Transforming a Stream With Operations

There are a ton of operations that you can use to perform functional-style computations on your streams. In this section, I’m going to cover just a few of the most commonly used stream operations.


The map() operation takes a lambda expression as its only argument, and uses this expression to transform the value or the type of every element in the stream. For example, the following gives us a new stream, where every String has been converted to uppercase:


This operation sets a limit on the size of a stream. For example, if you wanted to create a new stream containing a maximum of five values, then you’d use the following:


The filter(Predicate<T>) operation lets you define filtering criteria using a lambda expression. This lambda expression must return a boolean value that determines whether each element should be included in the resulting stream. For example, if you had an array of strings and wanted to filter out any strings that contained less than three characters, you’d use the following:  


This operation sorts the elements of a stream. For example, the following returns a stream of numbers arranged in ascending order:

Parallel Processing

All stream operations can execute in serial or in parallel, although streams are sequential unless you explicitly specify otherwise. For example, the following will process each element one by one:

To execute a stream in parallel, you need to explicitly mark that stream as parallel, using the parallel() method:

Under the hood, parallel streams use the Fork/Join Framework, so the number of available threads always equals the number of available cores in the CPU.

The drawback to parallel streams is that different cores may be involved each time the code is executed, so you’ll typically get a different output with each execution. Therefore, you should only use parallel streams when the processing order is unimportant, and avoid parallel streams when performing order-based operations, such as findFirst().

Terminal Operations

You collect the results from a stream using a terminal operation, which is always the last element in a chain of stream methods, and always returns something other than a stream.

There are a few different types of terminal operations that return various types of data, but in this section we’re going to look at two of the most commonly used terminal operations.


The Collect operation gathers all the processed elements into a container, such as a List or Set. Java 8 provides a Collectors utility class, so you don’t need to worry about implementing the Collectors interface, plus factories for many common collectors, including toList(), toSet(), and toCollection().

The following code will produce a List containing red shapes only:

Alternatively, you could collect these filtered elements into a Set:


The forEach() operation performs some action on each element of the stream, making it the Stream API’s equivalent of a for-each statement.

If you had an items list, then you could use forEach to print all the items that are included in this List:

In the above example we’re using a lambda expression, so it's possible to perform the same work in less code, using a method reference:

Functional Interfaces

A functional interface is an interface that contains exactly one abstract method, known as the functional method.

The concept of single-method interfaces isn’t new—Runnable, Comparator, Callable, and OnClickListener are all examples of this kind of interface, although in previous versions of Java they were known as Single Abstract Method Interfaces (SAM interfaces).  

This is more than a simple name change, as there are some notable differences in how you work with functional (or SAM) interfaces in Java 8, compared with earlier versions.

Prior to Java 8, you typically instantiated a functional interface using a bulky anonymous class implementation. For example, here we’re creating an instance of Runnable using an anonymous class:

As we saw back in part one, when you have a single-method interface, you can instantiate that interface using a lambda expression, rather than an anonymous class. Now, we can update this rule: you can instantiate functional interfaces, using a lambda expression. For example:

Java 8 also introduces a @FunctionalInterface annotation that lets you mark an interface as a functional interface:

To ensure backwards compatibility with earlier versions of Java, the @FunctionalInterface annotation is optional; however, it’s recommended to help ensure you’re implementing your functional interfaces correctly.

If you try to implement two or more methods in an interface that’s marked as @FunctionalInterface, then the compiler will complain that it’s discovered multiple non-overriding abstract methods. For example, the following won’t compile:

And, if you try to compile a @FunctionInterface interface that contains zero methods, then you’re going to encounter a No target method found error.

Functional interfaces must contain exactly one abstract method, but since default and static methods don’t have a body, they’re considered non-abstract. This means that you can include multiple default and static methods in an interface, mark it as @FunctionalInterface, and it’ll still compile.

Java 8 also added a java.util.function package that contains lots of functional interfaces. It's well worth taking the time to familiarize yourself with all of these new functional interfaces, just so you know exactly what’s available out of the box.

JSR-310: Java’s New Date and Time API

Working with date and time in Java has never been particularly straightforward, with many APIs omitting important functionality, such as time-zone information.

Java 8 introduced a new Date and Time API (JSR-310) that aims to resolve these issues, but unfortunately at the time of writing this API isn’t supported on the Android platform. However, you can use some of the new Date and Time features in your Android projects today, using a third-party library.

In this final section, I’m going to show you how to set up and use two popular third-party libraries that make it possible to use Java 8’s Date and Time API on Android.

ThreeTen Android Backport

ThreeTen Android Backport (also known as ThreeTenABP) is an adaption of the popular ThreeTen backport project, which provides an implementation of JSR-310 for Java 6.0 and Java 7.0. ThreeTenABP is designed to provide access to all the Date and Time API classes (albeit with a different package name) without adding a large number of methods to your Android projects.

To start using this library, open your module-level build.gradle file and add ThreeTenABP as a project dependency:

You then need to add the ThreeTenABP import statement:

And initialize the time-zone information in your Application.onCreate() method:

ThreeTenABP contains two classes that display two “types” of time and date information:

  • LocalDateTime, which stores a time and a date in the format 2017-10-16T13:17:57.138
  • ZonedDateTime, which is time-zone aware and stores date and time information in the following format: 2011-12-03T10:15:30+01:00[Europe/Paris]

To give you an idea of how you’d use this library to retrieve date and time information, let’s use the LocalDateTime class to display the current date and time:

Display the date and time using the ThreeTen Android Backport library

This isn’t the most user-friendly way of displaying the date and time! To parse this raw data into something more human-readable, you can use the DateTimeFormatter class and set it to one of the following values:

  • BASIC_ISO_DATE. Formats the date as 2017-1016+01.00
  • ISO_LOCAL_DATE. Formats the date as 2017-10-16
  • ISO_LOCAL_TIME. Formats the time as 14:58:43.242
  • ISO_LOCAL_DATE_TIME. Formats the date and the time as 2017-10-16T14:58:09.616
  • ISO_OFFSET_DATE. Formats the date as 2017-10-16+01.00
  • ISO_OFFSET_TIME.  Formats the time as 14:58:56.218+01:00
  • ISO_OFFSET_DATE_TIME. Formats the date and time as 2017-10-16T14:5836.758+01:00
  • ISO_ZONED_DATE_TIME. Formats the date and time as 2017-10-16T14:58:51.324+01:00(Europe/London)
  • ISO_INSTANT. Formats the date and time as 2017-10-16T13:52:45.246Z
  • ISO_DATE. Formats the date as 2017-10-16+01:00
  • ISO_TIME. Formats the time as 14:58:40.945+01:00
  • ISO_DATE_TIME. Formats the date and time as 2017-10-16T14:55:32.263+01:00(Europe/London)
  • ISO_ORDINAL_DATE. Formats the date as 2017-289+01:00
  • ISO_WEEK_DATE. Formats the date as 2017-W42-1+01:00
  • RFC_1123_DATE_TIME. Formats the date and time as Mon, 16 OCT 2017 14:58:43+01:00

Here, we’re updating our app to display the date and time with DateTimeFormatter.ISO_DATE formatting:

To display this information in a different format, simply substitute DateTimeFormatter.ISO_DATE for another value. For example:


Prior to Java 8, the Joda-Time library was considered the standard library for handling date and time in Java, to the point where Java 8’s new Date and Time API actually draws “heavily on experience gained from the Joda-Time project.”

While the Joda-Time website recommends that users migrate to Java 8 Date and Time as soon as possible, since Android doesn’t currently support this API, Joda-Time is still a viable option for Android development. However, note that Joda-Time does have a large API and loads time-zone information using a JAR resource, both of which can affect your app’s performance.

To start working with the Joda-Time library, open your module-level build.gradle file and add the following:

The Joda-Time library has six major date and time classes:

  • Instant: Represents a point in the timeline; for example, you can obtain the current date and time by calling
  • DateTime: A general-purpose replacement for JDK’s Calendar class.
  • LocalDate: A date without a time, or any reference to a time zone.
  • LocalTime: A time without a date or any reference to a time zone, for example 14:00:00.
  • LocalDateTime: A local date and time, still without any time-zone information.
  • ZonedDateTime: A date and time with a time zone.

Let’s take a look at how you’d print date and time using Joda-Time. In the following example I’m reusing code from our ThreeTenABP example, so to make things more interesting I’m also using withZone to convert the date and time into a ZonedDateTime value.

Display the date and time using the Joda-Time library

You’ll find a full list of supported time zones in the official Joda-Time docs.


In this post, we looked at how to create more robust code using type annotations, and explored the “pipes-and-filters” approach to data processing with Java 8’s new Stream API.

We also looked at how interfaces have evolved in Java 8 and how to use them in combination with other features we’ve been exploring throughout this series, including lambda expressions and static interface methods.

To wrap things up, I showed you how to access some additional Java 8 features that Android currently doesn’t support by default, using the Joda-Time and ThreeTenABP projects.

You can learn more about the Java 8 release at Oracle’s website.

And while you're here, check out some of our other posts about Java 8 and Android development!

  • Android SDK
    Java vs. Kotlin: Should You Be Using Kotlin for Android Development?
    Jessica Thornsby
  • Kotlin
    Kotlin From Scratch: Variables, Basic Types, and Arrays
    Chike Mgbemena
  • Kotlin
    Kotlin From Scratch: More Fun With Functions
    Chike Mgbemena
  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali
  • Android SDK
    Quick Tip: Write Cleaner Code With Kotlin SAM Conversions
    Ashraff Hathibelagal


Single-Page Applications With ngRoute and ngAnimate in AngularJS

Single-page applications allow you to refresh a certain portion of a web-page by routing any content stored in a separate .html file. By doing so, you do not reload your main page.

AngularJS provides a module named ngRoute exactly for this purpose.

Another useful module of AngularJS is ngAnimate, which makes it easy to animate with certain CSS classes.

In this tutorial I will try to explain each step thoroughly, although you still need a basic knowledge of AngularJS in order to be able to follow.

Starting With a Main Page

Basic Structure

This index.html file is going to be our main page where we have both fixed and routed content.

I will start with a basic HTML document and include all the necessary libraries along with our custom stylesheet named style.css and a JavaScript file angularApp.js.

 Now I add two DIVs with id names of fixedContent and routedContent inside a mainWrapper DIV.

routedContent is also wrapped inside another DIV named wrapper. That is because the routedContent should be absolute positioned relative to a parent DIV due to the fact that during routing animation, two different pieces of content clash with each other.

As the id names imply, fixedContent will be the static content of our main page, and routedContent will be dynamically changing upon user interaction.

In order to define an Angular app in our HTML file, we need to use the ng-app directive. Since the whole page will be an Angular app, we need to assign this directive to the mainWrapper DIV.

We also need the ng-view directive, which tells the DIV it is assigned to display the routed page content.

Now our index.html file looks like this:

Navigation Menu

We need a navigation menu in order to route different pieces of content to ng-view.

We are going to use the ul and a elements to create a simple horizontal menu. Below you can see the HTML snippet for the menu structure.

By default, the ng-route module uses the ! prefix. However, here we only use # in front of our pages to be routed. This is done with the hashPrefix attribute used in the configuration, which I'll explain later in the related section. For now, take it as it is.

Our final HTML file is as follows:

Styling the Main Page

Since this tutorial focuses on AngularJS, I am not going to detail the CSS styling. If you have former CSS knowledge, style the page as you wish. Otherwise, you can use the styling I provide below.

Pages to Be Routed

Each page that will be routed to DIV with the ng-view directive inside the main HTML file can have a unique HTML structure and CSS styling.

Let's start with page1.html.

Since we want a specific styling for each page, we need separate CSS files for each page. Therefore, we also create a file named page1.css, which will contain the styling rules of page1.html.

The basic HTML structure for page1 is as follows:

At the top, we linked to the CSS file that will be styling the page, and we declared a DIV with id name of page1, where the whole content will be laid.

I will keep it simple, but it is completely up to you how to structure the HTML file. Just bear in mind that your container will always be the DIV to which the ng-view directive is assigned. So everything in your routed pages will be relative to that DIV.

The styling of page1.html is given below:

The other three pages can be totally different, but for the sake of simplicity I am just using the same template for each HTML page and slightly different CSS files (different h1 text-colors).

page2.html & page2.css

page3.html & page3.css

page4.html & page4.css

Setting the ngRoute & ngAnimate in JavaScript

So far we have completed all the necessary HTML and CSS files. Now it is time to write the JavaScript code that controls the routing and animation.

Since our ng-app directive is named mainApp, we use this id in the module function. We also need to include the ngRoute and ngAnimate dependencies.

mainAngular = angular.module('mainApp',['ngRoute', 'ngAnimate']);

Now we have access to $routeProvider and $locationProvider.

We are going to use the $routeProvider to manage the routings and $locationProvider to change the hashPrefix, which is set to ! by default.

We use .when('/page1', {templateUrl: 'page1.html'}) to define the page to be routed when <a href="#page1">Page1</a> is clicked in our main HTML file.

We repeat the same line of code for each page to be routed. At the end, we use .otherwise({redirectTo: '/page1'}), which handles unexpected page names. If you try to visit an undefined page name, say page5, you will be redirected to page1.

The complete JavaScript code is below:

Extra Note: If you wish to add a specific ng-controller directive for any pages to be routed, you can handle this inside the $routeProvider.

An example for page1:

In the end, our page should look like this, and you should be able to navigate between pages with no transition animations.

Final result after styling and routing

Animating the Page Transitions

Now it is time to animate the route transitions.

For animation purposes, AngularJS has built-in CSS classes thanks to the ngAnimate dependency.

Those classes that we are going to use are:

  • ng-enter: The starting CSS styles for the enter animation.
  • ng-enter-active: The finishing CSS styles for the enter animation.
  • ng-leave: The starting CSS styles for the leave animation.
  • ng-leave-active: The finishing CSS styles for the leave animation.

So the routed content which is coming into the main page has a transition from ng-enter to ng-enter-active. Likewise, the content leaving the main page has a transition from ng-leave to ng-leave-active.

We have to attach the above mentioned classes to our routedContent class.

An example transition is given below. You can either design your own transition animations or use this one inside your style.css file.

Below is the final result of the project on Plunker.


In this tutorial, we covered how to create SPA applications with the ng-route module of AngularJS, and then we animated the transitions through the CSS classes of ng-animate.

By using only four CSS classes provided by ng-animate, you can achieve various animations. You can always attach extra classes to have more control over the transition animations. For example, you can make your page transitions direction-aware.

I also mentioned that by attaching the controller directive to each specific page inside the $routeProvider, you can achieve extra control over each page.

JavaScript, with its libraries such as Angular, has become one of the de facto languages of working on the web. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

I hope this tutorial gave you an overall idea of how to utilize the ng-route and ng-animate modules together.

November 13 2017


Get Started With Vue Router


Routing becomes an important feature to put in place when you have many components. Thanks to the awesome Vue.js team, this is easy using vue-router.

In this tutorial, you will see how to use vue-router while building a simple Vue.js application.

Set Up the Application

You will make use of Vue-CLI to set up your application for this tutorial. If you do not have it installed already on your machine, you can do so by running:

With that done, you can set up your application using the command below.

You are going to be asked some questions. One of these questions is: Install vue-router? For that, enter y.

Navigate to your project folder from your terminal:

Run the command to install all dependencies:

Start your development server by running:

If you want to install vue-router manually, you can use the command below.

Integrate Vue-Router

When using Vue-CLI, the router gets activated by default. You can see that in your src/router/index.js file.

  1. Vue is imported from vue.
  2. Router is imported from the vue-router package.
  3. HelloWorld is imported from the components folder. We'll talk more about this later.
  4. Router is mounted as middleware to your project.
  5. A default route configuration is created. The route is an array of a JavaScript object. It consists of a path, name, and component. The path gets appended to the URL of your web application. The route created above is meant for the home page. You can change the path to /hello, and it will no longer work for the home page. It will only be triggered when you visit the /hello path of your application. The component tells the route the component you want to load when that path is visited. This is the reason you imported the HelloWorld component. This route is exported as Router.

The exported Router has to be imported in your src/main.js file. This is important for the routes to work. This is taken care of when working with Vue-CLI. Your src/main.js should look like this:

  1. The router is imported from your router folder.
  2. The imported router is used when creating a new Vue instance.

Standard Routes

The route you saw above is an example of a standard route. A standard route is one having a path, component, and name. Let's create our own route. Try this part out yourself using the flow below.

  1. Create a new component called Pack. You need to have some dummy text.
  2. Go to your src/router/index.js, import the new component you created, and add a new path.
  3. Open your browser and point to the new path.

I bet you were able to do that on your own. Let's try it out together.

Here is what my Pack component looks like.

Open your router file, and it should be looking like this.

Now point your browser to http://localhost:8080/#/pack and you should see your new page.

Routes With Parameters

The routes you have made so far are static routes. Let's see how to make dynamic routes. Open your routes file and add another route like this.

Here you have your path set to /user/:id; the :id defines a parameter that allows you to pass values to the routes via the URL. From the above, it is possible to have http://localhost:8080/user/23.

The value passed to the route component, in this case, is 23, and this can be accessed in the User component.

To try this out, create a new component called User. In this component, you want to be able to access the route parameter passed through the URL. This parameter will be saved in a variable called id, and the value outputted in the template. Here is what the component should look like.

Now point your browser to http://localhost:8080/#/user/123 and you will see the parameter displayed. Change from 123 to something else, and the new value will be displayed.

Child Routes

In Vue.js, it is possible to nest routes by defining children routes. This is possible using the children property provided by Vue.js. The children routes are passed as an array of objects. In your test app, you will create a child route for profiles. The child route will be given a path and a component.

First, create a new component called Profile.vue. Here is what it should look like.

Open your router file. The first thing you want to do will be to import the Profile component. After doing that, add the children property to the route for the User component so your route file looks like this.

Now you will be able to access this new component when you point your browser to http://localhost:8080/#/user/13/profile.

Link to Routes

At this moment, the only way to navigate in your application is by entering the URL path in the browser. This is not how you will want to build a real-world application. To link to routes in Vue.js, you'll have to make use of the <router-link> element.

Here is how it is used:

For children routes, here is what it should look like.

The to attribute contains the path to the route.

To set that up in your application, open your App.vue file and make it look like this.


Navigating from one view to another is now very easy. You can go ahead and add more views. Try adding a child route to the profile route, so the path becomes http://localhost:8080/#/user/13/profile/child-path.

In this tutorial, you learned how to set up routing in Vue.js. Going forward, you should have no issues with routing in a Vue.js application. While working on this application, you also learned about the route and params object.

I hope you enjoyed yourself.

November 10 2017


Implementing an Event Bus With LiveData

Final product image What You'll Be Creating

At the last Google I/O, the Android team released a set of powerful Android Architecture Components. They call it:

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

If you haven't learnt about them, you are strongly advised to check out our awesome series here on Envato Tuts+ about Android Architecture Components by Tin Megali. Make sure you go dive in! 

  • Android SDK
    Introduction to Android Architecture Components
    Tin Megali

In this tutorial, I'll show you how to use the LiveData components from the Android Architectural Components to create an event bus. An event bus can be used to effectively communicate between Android components or between layers of your application—for example, communicating to an Activity from an IntentService that a file has finished downloading. 

We'll build a very simple app that triggers an IntentService to do some work—from an Activity. Our IntentService will then communicate back to the Activity when the work is completed. Our communication channel will be from the LiveData library. 


To be able to follow this tutorial, you'll need:

You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.

1. Create an Android Studio Project

Fire up Android Studio 3 and create a new project with an empty activity called MainActivity

Android Studio new project screen

2. Add the Lifecycle Components

After creating a new project, specify the LifeCycle and the LiveData artifacts in your app module's build.gradle. Note that as of this writing, the new architectural components are now in a stable version. So this means you can start using them in production apps.