googleads
Laravel Rest API - How to Build REST API with Laravel 5.5/ Laravel 5.6
preloder
API Laravel Standard Web Development

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

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.

 

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.

 

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.

 

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.

 

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.

 

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.

 

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!

 

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!

The following two tabs change content below.

Vignesh M

An energetic Senior Software Engineer has strong desire in Web development. With 5 years of experience in Angular, PHP, Hybrid app development he always strives to come up with the Smart Solutions to accomplish the complex tasks. Technologies apart, Ask him anything, be it Games, Bikes, Travel spots, Computers, Books, Politics or whatever He ll be mastering it all!

6 thoughts on “Laravel API – How to Build REST API with Laravel 5.5 / Laravel 5.6”

  1. Hello Vignesh,
    This is really excellent post you have shared here.
    Let me also try this method.
    Thanks
    Jamie

    1. Hello Jamie,
      I am glad my post inspired you to try, Thanks for reading. Please do reach out if you need any help in trying this.

    1. Hi Anon,
      Thanks for dropping a comment. The code is actually copied from a real project and reduced to very minimal for the blog. If you can be specific about the errors, I am really happy to fix them here.

  2. Thanks for your clear and nice articles regarding Laravel API and Laravel Resources, I am starting to learn Web Api in Laravel, If you have sample or articles regarding passing multiple parameters to Laravel API via Ajax, Please do Share.

  3. Hi Jonas,
    Thanks for dropping by. It’s not clear that you need help in handling whether the frontend or backend part of the Ajax API call, assuming you have mentioned about reading the data sent via Ajax in Laravel, Please go through this StackOverflow answer, https://stackoverflow.com/a/44823562.
    If you didn’t find what you’re looking for there, kindly reply me and I am really happy to help.

Leave a Reply

Your email address will not be published. Required fields are marked *