At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

, ,

Laravel API – How to Build REST API with Laravel 5.5 / Laravel 5.6

  • By Vignesh M
  • February 8, 2018
  • 1304 Views

Laravel is an excellent framework which nicely balances the gap between Symfony (The powerhouse of an enterprise framework) and Codeigniter (the small, easy learning framework). That’s the reason why Laravel became the de-facto choice for most developers and organizations.
With the right choice, let’s step into the concept of “Build a REST API with Laravel.”
In this post, I want to show you how to build a REST API with Laravel framework and with the new addition to Laravel 5.5 it would be even easier like never before. I assume that you have got the PHP development environment set up already, So Let’s directly start from creating a new Laravel project.

Creating a project

Open a new terminal window and navigate to /var/www/html folder and then type the following command to create a new Laravel project.

composer create-project --prefer-dist laravel/laravel blog

 
The above command is pretty self-explanatory; we are creating a new project using the distribution (stable) version of Laravel into the blog folder. This will create a new folder named “blog” into your current directory. Now, navigate to the blog folder in terminal and type the following command.

Cd blog
php artisan serve

 
The above comment will start the built-in web server of PHP which is listening on the port 8000, so you can navigate to http://localhost:8000 to see the defined Laravel homepage.
If you see above the screen in your browser, it means that you’ve successfully installed Laravel on your machine.

Create a route

Inside the routes directory, you can find 4 files based on the category of the route,
These are the list,

  • The api.php – our main working area for this article.
  • The web.php – For browser-based routing,
  • The console.php – For terminal scripting and
  • The channel.php – For event channels.

So go ahead and create your first route in that file, there are quite a lot of ways to define routes and their functions in Laravel which will require a complete post for itself. So I will try to keep this routing part as a minimal working level, for more configuration options you can always visit the Laravel docs. Click Here to Read
The below is a sample route definition for RESTFUL endpoints for CRUD operations of the posts. You can even finish this with the one line resource controller and resource routes. But I like the flexibility of having every route separate.
Note: I also used route specific middleware to check the validity of the UUIDs which is given in URLs, this will return 404 if the UUID provided in the URL is not valid. Now let’s go ahead and create our posts controller.

Route::group([
'namespace' => 'v1',
'prefix' => 'v1'
], function() {
Route::post('/posts, 'PostsController@create');
Route::get('/posts', 'PostsController@list');
Route::get('/posts/{uuid}', 'PostsController@get')->middleware('uuid.validate');
Route::put('/posts/{uuid}', 'PostsController@update')->middleware('uuid.validate');
});
});

 
The below snippet is written only for this tutorial, so it doesn’t have all the bells and whistles like Validation, etc. but you can see how I am returning the success and error messages and that’s our concentration for now.

use App\Http\Resources\Post;
class PostsController extends Controller
{
public function create(Request $request)
{
try {
$post = new Posts();
$post->setUUID(Uuid::uuid4());
$post->title = $request->input('title');
$post->content = $request->input('content’);
$post->category = $request->input('category’);
$contact->save();
return response(new Post($contact), 201);
} catch (\Exception $e) {
Log::debug($e);
throw new HttpResponseException(response()->error());
}
}
}

 
Here we are creating a new post on our blog. I used UUID package to generate identifiers for each post. You can notice that I am calling the response function passing in a new instance of the post Resource.

Resources

Resources are new additions that are included in Laravel 5.5, Using Resources you can control the response of your data and how it’s going to be modeled regardless of the data model you’re using inside of your application. Because once your API gained some users, it’s advisable to you for not introducing any breaking changes.
So the resources will give you the way to decouple your API response from your database structure. Previously this was done using Fractal an external package from The League. Resources are Laravel’s homemade alternative to Fractal, and it is easier to work with it inside of the Laravel.
The Post resource will look something like this.

use Illuminate\Http\Resources\Json\Resource;
class Contact extends Resource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
"id" => $this->getUUID($this->uuid),
"title" => $this->title,
"content" => $this->content,
"category" => $this->category->only(['id', 'name']),
];
}
}

 
The toArray method is the place where we’ll build up the response JSON. The $this here refers to the model instance you passed into the constructor of this resource, so you can call all the methods like how you normally call in your model. This includes Relationships, collection methods, and traits. So the below screen shows the return response of JSON.

{"id":1,
"title":"Laravel REST API development",
"content":"Laravel is a good balance...",
"category":{
"id":1,
"name":"technical"
}
}

 
The good part is now you can modify your database column name, even change the model with a different one without affecting the API because the Resource indexes aren’t going to change unless you do. You have the control of which change you expose to the consumers of your API, and it’s a good sign that your API is great.
Well, this would be good for returning a single entity, but what if you’re returning a collection of database entities; No worries, Laravel has got your back!

class PostsController extends Controller
{
public function list(Request $request)
{
try {
$creator = $request->get('userSession');
$contacts = Posts::where('created_by', $request->input('id'))->get();
return response(Post::collection($contacts), 200);
} catch (\Exception $e) {
Log::debug($e);
throw new HttpResponseException(response()->error());
}
}
}

 
The above is the list method of the same posts controller but this time we’re returning the collection of posts. To do this, we don’t have to make any changes to the post resource. Luckily, Collection method of Laravel takes care of this for us. With the new Resources addition to Laravel 5.5, there are lots more you can do.
Read here for more Details
For the scope of this tutorial we just touched the basics. We would discuss briefly this in upcoming blogs. Parallely, I am glad to hear back from you about your opinions and experiences on using Resources in Laravel. And if you are looking forward to more technical blogs about web development and mobile app development follow Agira Technologies a fast growing IT company, exploring upcoming technologies and exposing everything to help the right people at right time. For more queries always reach us. We love to hear from you!

Vignesh M

An energetic Fullstack developer/Tech Lead and has a strong desire in Programming. With 6.5 years of experience in Angular, Javascript, Laravel PHP, Ionic, and Flutter, he always strives to come up with Smart Solutions to accomplish complex tasks.He is also interested in Video games, Motorcycles, Books, Movies, History.