Series: Build an app with Laravel5 (backend) and Angularjs (frontend) – Part 1

Laravel & Angularjs works really well together, if used in a correct way. In this Laravel & Angularjs Series, we will be creating an app where Laravel will be used for creating an API and Angularjs for consuming that API.

This series is aimed at those, who want to completely separate their frontend and backend. This is the most common use case in hybrid app development using phonegap or ionic framework.

So without further due, let’s get started with the Laravel Part.

Install Laravel & Create New Project

First Install Composer By Following this guide.

Then, download the Laravel installer using Composer.

Once successfully installed, you can type laravel new command to create new Laravel project.

After successfully creating the project, make sure your webserver is running (you can use XAMPP, LAMP, MAMP), now go into the project directory and type.

Now you can open the following url.

http://localhost:8000

And you will see the Laravel front page.

Now we will add a package called Laravel-5-Generators. This Laravel package provides a variety of generators to speed up your development process.

You can install the generator via composer as:

Now open the app/Providers/AppServiceProvider.php file and updated the register function as,

Now run,

You will see new commands added in the make:* section.

Setup DB, Create Migration & Insert Dummy Data

Setup DB

First, rename the .env.example file in the laravel installation root directory to .env

now open the .env file and change the following:-

DB_HOST=localhost
DB_DATABASE= your_database_name
DB_USERNAME= your_database_username
DB_PASSWORD= your_database_password

Create Migration

Next step is to create the migration, as the laravel documentation says, Migrations are like version control for your database, allowing a team to easily modify and share the application’s database schema. Open the terminal and type the following command to create the migration.

You can see the created migration in database/migrations folder. Open the migration file and replace it with this code.

Here you can see we have added the id, joke, user_id and timestamps fields. Where id is auto incrementing, joke is the body of the joke and user_id will be used for the user who will submit the joke. Here there are two functions one is up and other is down. The down function is the exact opposite of the up and will be used if we want to revert back the migration.

Now run the following command.

Now have a look at the database, you can see the new jokes table there. Along with jokes table, laravel creates three other tables namely users, migrations, password_resets.

Now to demonstrate the down function. Let’s say we want to change the joke field with body. What you can do is, change the field in the migration table.

Now run the following commands.

Now open the database and check the structure and you can see the jokes table joke field renamed to body.

Insert Dummy Data

The next step is to insert the dummy data that we can use throughout the  development process. For inserting dummy data we will use a package called fzaninotto/faker.

First we need to install this package,

Now first create a Joke Model by typing:

Now create the seed file which will be used to insert dummy data.

You can see the created seeder file in database/seed folder. Open JokesTableSeeder.php and add the following.

At the top you can see, we have added App\Joke that makes us available the jokes model and we are using to create new jokes as Joke::create. Here you can see we have used $faker object, it is availabe through package. For the list of all the available functions, you can have a look at their documentation.

Now Create the new seed file for users table as.

Now open UsersTableSeeder.php and add the following.

Here you can see we have added App\User at the top, which means we are requiring user model. It is availabe through default laravel install.

The next step is to open DatabaseSeeder.php and add the created seeder classes.

Now before using the seed command we need to do one more thing. Open the Joke Model file. This will be inside app root folder and add the fillable array inside the class as.

By using this we can mass insert values in the database table.

Now the last step is to run the db seed command as.

After that you can see the database table with all the dummy entries.

Creating & Testing Routes

In the last section we successfully created the database, created migration and prepared seeder classes. In this section we will create our routes or api end points which we can hit to get data.

Open the routes.php file and add the follwing code:

Now we need to create the JokesController, for this we will use generators like,

This command will create the jokescontroller with all the required methods.

Now run this command:

You will see output similar to this:

CWindowssystem32cmd.exe_2015-11-05_09-52-51
Now we can add the prefix to all these routes as, in the routes.php updates the code as:

Now your output will look like:

CWindowssystem32cmd.exe_2015-11-05_10-13-08

Now open the JokesController.php, add the following at the top,

Now update the index method as:

Here we are using the Eloquent ORM, which makes it easy to work with database. If you don’t know about eloquent, have a look at the Eloquent Documentation.

The Joke::all() will return all the rows from the jokes table.

Now run the server as:

and open:

You will see all the records from the jokes table, also it is worth mentioning, the data is casted to json automatically.

2015-11-05_10-31-59

Now using the browser is good if you want to test GET request, but if you want to test POST, PUT, PATCH, DELETE request we probably will not use browser for this. So, for that scenario we can use Curl, which is perfectly fine or we can use a utility called POSTMAN which is a chrome extension. That makes it really easy to test all the requests. Let’s see how we can test our api with postman. Install the postman extension and open postman:

2015-11-05_10-39-30

Here select the request (GET, POST etc.), enter url and press send, the output is similar to the one we saw in browser but this will prove more useful once we get to other requests.

Now, yes it is a working api but there are some problems with it:

  • It is not a good idea to return all the results at once.
  • We are showing the exact structure of the table.
  • We are sending any error message and response codes.

Now in the following sections, we will work on improving that api.

Responses & Codes

Now let’s add the status codes to the data, the available status codes are:

2015-11-05_10-53-24

Updated the index method in the JokesController.php as follows:

Now open the /api/v1/jokes url in the postman, you can see status returned as 400.

2015-11-05_10-58-00

The 400 is mainly for the bad request, so the status that we probably want to return is 200, so change the code as follows:

Now again hit the endpoint/url in the postman, you can see status returned as 200.

Now let’s implement the route for getting single joke, we can see from php artisan route:list, when we get to api/v1/jokes/{jokes} we are calling the show method and will get single joke.

So update the show method as follows:

Now try accessing this route, if the joke with specific id not exists we will get the error response and if it exists we will get the 200 response.

If the joke exists:

2015-11-05_11-07-10

If the joke doesn’t exists:

2015-11-05_11-07-47

 

Transforming Data

At that point, we can see that, we are returning the exact db table structure, and it is not a good idea, it may be possible we only want to show specific fields and don’t want to show the fields name as in the table. So for this we can transform the data before displaying.

Add the following two methods at the bottom of the JokesController Class in the JokesController.php,

Now update the index and show methods as:

Now again hit the routes and you will see the transformed data.

Eloquent Relationships

Using Eloquent Relationships we can relate two tables.

First we need to define the relationship between the two tables users and jokes and then we can join the tables data.

Let’s start by adding a relationship:

open the User.php model file and add the following method:

and open the Joke.php model file and ad the following method:

Now open the JokesController.php and update the show method as follows, before that add the following code at the top:

Now update the show method as:

and our updated transform method with look like this:

So, our updated show method code will look like this, here first we are joining User table data with the jokes tables, also we are finding the previous and next joke and then we are adding them to the response. So our response will now look like this:

2015-11-05_11-33-47

Where submitted_by data is coming from users table after joining.

Implement POST, PUT, DELETE requests

Open JokesController.php and update the store, update and destroy methods as follows:

First add the following code at the top of the file,

Now update the following methods:

To test POST request, open postman and send post request as follows:

2015-11-05_11-49-18

Similarly, you can test Update and Delete requests.

Pagination

For pagination, Laravel provides a very simple method called paginate(), let’s see how we can implement pagination. Open JokesController.php and update the index method as follows:

Now access the route, you will see error something like this,

2015-11-05_11-58-32

The problem is now we need to update the transformcollection method in the JokesController.php as:

Now go to the route you will see the paginated result, like this.

2015-11-05_12-00-44

Currently, we are hard coding the pagination to 5 elements but we can use query string to specify the no. of elements. The updated index method will look like this:

Here we are checking to see, if the limit is present as query string, if yes use that value otherwise the no. of elements are default to 5.

Implementing Search

Now let’s implement the search functionality, update the index method as follows:

Now you can test the search as follows:

2015-11-05_12-07-38

Adding JWT Auth

Now we will add the security to the routes, such that only the authenticated users can request the data, otherwise they will get error.

Let’s start with basic auth, that laravel provides by default, open the JokesController.php and add the contructor function as:

This means we are using basic auth on all routes. When we now try to view the route in the browser, we will first need to signin and then we see the data like.

2015-11-05_12-12-26

Now, if we type the correct credentials, only then we can see the data.

But we won’t be using this for our api, for api’s it is better to use token based authentication, which means whenever the user authenticates he will be provided with the token, and the user will then send this token with each request and if the token is valid, only then the data will be displayed.

For Token Based Auth, we will use a laravel package called jwt-auth ,

First open the composer.json and add the following item to the required array,

Now run the following command:

It will download the jwt-auth package.

Now Open config/app.php file and add the following item to the providers array:

Also in the config/app.php, add the following items to the aliases array:

Now publish this package from command line as:

Now you will see a new file in the config folder called jwt.php, Now we need to generate jwt specific key from command line as:

Now you can see the key in the secret field changed to new key.

Now open the routes.php and add the following routes:

Add the following middleware to the construct method in the JokesController.php:

 

Now we need to make the AuthenticateController from the command line as:

Now open the AuthenticateController.php and update the file as follows:

Now try to hit the route, /api/v1/jokes, you will get an error token not provided like this:

2015-11-05_12-33-09

Which means, we first need to generate token that we can generate by sending post request to api/v1/authenticate with email and password as following:

2015-11-05_12-36-08

Now you can send the requests with this token and then you will get the result as expected.

2015-11-05_12-38-28

Tackling CORS

Now our api is working fine, but there is last thing to take care of, now let’s say if we put this api online, no one will be able to access the api due to cross domain restrictions. So to overcome this we can install a Laravel package called laravel-cors.

First install the package using composer:

Now add this package to config/app.php file’s providers array as:

Now to use this package, open the routes  file and update the routes as follows:

Wrapping Up Part 1

Hopefully this tutorial was helpful and you have created your first API by the end of it.

Feel free to leave any feedback or questions in the comments below and let me know if there’s anything you need help with or if I can clarify anything.

Thanks @jeffrey_way (laracasts) for his awesome screencasts, learned lot from him & jwt-auth inspiration by @ryanchenkie.

See Part 2 of this series, where we will create an app with AngularJS using this API.

Thanks.

Please Consider Donating (Click Here)