How to Create APIs in Laravel 5.5 using API resources

In this post, I will show how easy it is to use API resources to build REST APIs. In the previous Laravel REST API tutorial, I have used Fractal 3rd party library to control API response data. In Laravel 5.5, we now have API resources and these resources are literally developed based on Fractal.Now we can transform data without Fractal with API resources.

What is Resource

A Resource class is a way to transform data from one format to another. For example, if you have a comment model and you want to manipulate the data or remove certain fields from the model before sending that in our response, it is difficult without using some sort of data transform layers like API API resources or Fractal.

How to Create APIs in Laravel 5.5 using API resources

So let’s start your first REST server-

Creating the Laravel app

Create the Laravel app called “todo” with the below command

On successful installation, you will get similar output on your console –

Above command will create a todo directory and all project related files and directories will be downloaded into “todo” folder. Now change the directory to todo and issue artisan command to serve the application.

Configure Your Database

Create a database and edit .env and fill it with your database settings. This article assumes a MySQL database.

Create Migration File

Below command set up the basic migration scripts that we’ll be using to create the database table.

Now required migration file is in place, so let’s add a table column as shown below.

Edit app/database/migrations/SOME_DATE_create_tasks_table.php and edit and update the up() and down() methods:

Add Sample Users and todos

We gonna use Laravel’s seeds to create a few sample users and todos.

Let issue following commands to create seeder class from your root of the project.

Generated seeders by the above commands will be placed in the database/seeders directory. In our case, we have two seed files called UsersTableSeeder.php and TasksTableSeeder.php.

Update seeder run methods as shown below
UsersTableSeeder.php

TasksTableSeeder.php

Next, make sure that seeder class gets run when the database is seeded. Edit app/database/seeds/DatabaseSeeder.php

Add Model Factories

Next, create app/database/factories/UserFactory.php and app/database/factories/TaskFactory.php and place below code blocks

Create Task Model

Laravel comes with a User model setup, so let’s create a model for our tasks table.

Create a modal with

since you are following Laravel naming conventions you don’t have to change anything in the task model.

Run the Migrations

Below are the Laravel’s artisan commands and issue below commands from your project root. These commands will create those tables and inset sample users and tasks to the database.

You might get following error –

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email))
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

To fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:

We gonna build following endpoints –

Create Task Controller

Now define your api routes in routes/api.php

Create a Task recource

Now let’s create a resource for Task, which will transform the eloquent model into the proper dataset, which we can return to the end user.

Above command will generate a file called Task.php inside app/Http/Resouces

Now update Task.php toArray method with below code –

Now let use above generated Task resources inside Task controller –

How to access

You can use CURL or any rest client like postman or advanced rest client

Using curl, you could do something like this –

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.


DMCA.com Protection Status