Laravel has over the years built a reputation for making developers productive. Built with Convention over Configuration, it enables developers to focus more on the application logic over all the other routine work that goes into building an app.
Am I the only one that kinda wants this short-cut to creating Class@method strings for controller routing? ? pic.twitter.com/Oo3doIpXBJ
— Taylor Otwell ?♂ (@taylorotwell) December 26, 2017
While it’s great for building web applications, it hadn’t been my first choice for building APIs because the entire bag of goodies that Laravel provided was great for webapps but not much for APIs.
This was until Laravel released Passport in ver 5.3 for implementing OAuth2 standard for your API. The next moment of clarity came when they released API Resources in ver 5.5. With APIs you need to build a translational layer that transforms model data into JSON responses, API resources in 5.5 makes this easy to achieve with an artisan command.
When you build APIs, 9 out of 10 times you need a mode of authentication to secure your endpoints and identify the consumers of your service. APIs contrary to web applications do not utilise login forms and maintain session states, they use tokens. OAuth2 is an industry-wide standard for implementing authentication and authorisation for APIs and Laravel Passport sets up OAuth2 server with API authentication in minutes. You can watch this tutorial to know more about it.
When it comes to building a translational layer, this one is a delight. I was working on an API that would accept a patient’s medical conditions as request parameters and return suggestive treatments as a response. The database of treatments had numerous fields but the API required to respond with only a few.
Laravel provides a method, toArray(), to translate the model data to a serialisable array that can be sent back in responses. I could also utilise the relationships between entities, with the help of Eloquent relations and the method collection().
public function toArray($request)
'id' => $this->study_id,
'name' => $this->study_name,
'locations' => Location::collection($this->locations).
Pagination was another thing that came out of the box with the method paginate(). I could also add metadata to the payload using the method with(). The JSON response showcase below could be built in a span of few hours.
If Laravel can take care of the routine tasks for building the API, developers can focus more time on the business logic. In one of the APIs that ColoredCow worked on, the timeline for the development phase was reduced to a month with Laravel when it was originally projected to be two months with CodeIgniter. We could spend the invest more time on improvising the algorithms, which meant better results from the API.