DEV Community

Cover image for HOW TO USE RESTFUL RESOURCE CONTROLLERS IN LARAVEL
Pedro Pessoa
Pedro Pessoa

Posted on

HOW TO USE RESTFUL RESOURCE CONTROLLERS IN LARAVEL

Laravel is a free and open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern and based on Symfony (wiki).

The Framework provides a lot of features to help developers improve APIs and CRUD (Create, Read, Update, Delete) Applications, in both cases the most used and recomended feature is named RESTful Resource Controllers, before we use this Feature, it is important to understand what API Resources are about, what these features are and what they are made for.

 

API Resources

Api Resources are HTTP protocol methods accessed by a client machine which requests a service provided by the server, for example, the GET method, is responsible for requesting a particular record or a set of data stored on the server. A resource-oriented API is generally modeled as a resource hierarchy, where each node is either a simple resource or a collection resource. For convenience, they are often called a resource and a collection, respectively. A collection contains a list of resources of the same type (See more).

Below we can see a table referring to the main HTTP protocols and their responsibilities within the server

HTTP METHOD RESPONSABILITY
GET Get a particular record or a set of data.
POST Create a given record requested by a client machine.
PUT Update a record on the server.
DELETE Delete a record on the server.

 

Restful Resources Controllers

Developers usually create their Controllers and Models through the Artisan command directives, provided in the installation of the Laravel project, but what many developers do not know is that it is possible to create a Controller with ready-made methods that are directly related to the previously mentioned HTTP methods, for this we must use the --resource option after the controller creation command, for example:

php artisan make:controller ApiController --resource
Enter fullscreen mode Exit fullscreen mode

When running this command in your console, Artisan will create a new Controller in the app/Http/Controllers folder with some predefined methods, all these methods are related to API resources, all methods generated by the command have comments in the PHP DOCS standard (See More), with a brief description of each one's functionality.

For example, the method responsible for returning a listing (whether it has pagination or not) is called index(), in the examples below, we will use the case of a Model User.

 

Listing itens

By default, when a method inside a Controller returns a resource from an application's Model, Laravel returns a Response in JSON format, so we don't need to specify the method's return type, despite being a good practice.

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    return User::all(); // Can be overridden by a pagination method
}
Enter fullscreen mode Exit fullscreen mode

 

Creating new Itens

To create new records in the database, Laravel creates two new methods, a method called create and another method called store, note that, by default the store method receives a request as a dependency injection parameter, this happens because, unlike the create method, the store method is only responsible for creating a new record in the database, unlike the create method, which, by default, should return a view with a form in which the system user must fill it out in order to be inserted into the database through the store method. In this case, we will only use the store method, but know that it is possible to use the create method in any type of Laravel application, preferably one that returns views and styles.

/**
* Store a newly created resource in storage.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\Response
*/
public function store(UserRequest $request)
{
    /**
    * Can be overwritten by a validation coming from
    * a different request object
    */
    return User::create($request->validated()); 
}
Enter fullscreen mode Exit fullscreen mode

 

Updating Itens

Following the pattern of the creation methods, the update methods are also divided in two, in this case, the edit method will be responsible for returning a view with a form responsible for sending the data that will be updated in a certain item in the system, while the update method will be responsible for updating a certain item in the application directly in the database.

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    /**
    * Can be overwritten by a validation coming from 
    * a different request object
    */
    return User::update($request->validated()); 
}
Enter fullscreen mode Exit fullscreen mode

In some more recent versions of Laravel, you can replace the int $id parameter with a parameter that makes more semantic sense within the application, for example User $user, this way, Laravel automatically searches the database for the user by the ID received from the request and put it inside the $user variable, making your code cleaner and more semantic.

 

Deleting Itens

Different from the creation and update methods, the method of removing items from the database is unique, the method called destroy is responsible for destroying an item from your API. The method takes an id parameter, which is used to find the user in the database and then delete it.

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    User::findOrFail($id)->delete();
}
Enter fullscreen mode Exit fullscreen mode

Note that it is also possible to change the id parameter by the object to be searched, as in the editing method, in this way, the method would receive the User $user parameter and then remove it directly with the delete method , using $user->delete(), leaving the code cleaner.

 

Get specific Item

Through the index() method we can see all items within a table in the database, but Laravel also creates the show() method, which is responsible for returning a specific item from the database. The show() method receives, by default, an int $id parameter, which would be the id of the item that the request should return, as shown below.

/**
 * Display the specified resource.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function show($id)
{
    /**
    * It can be rewritten by directly 
    * passing Model as a method parameter, as shown above.
    */
    return User::findOrFail($id);
}
Enter fullscreen mode Exit fullscreen mode

 

Routing

After creating the Controller and its methods, now we must write the routes that correspond to each method, however, in addition to the length of the code, this could make the code less clean than usual. To solve these problems, Laravel provides a creation method of routes called resource, which configures each parameter and method automatically. You can check more features, like adding middleware in the route, or adding exceptions for certain methods through the official documentation (See more).

Route::resource('users', ApiController::class);
Enter fullscreen mode Exit fullscreen mode

 

Conclusion

After learning a little more about How To Use RESTFUL Resource Controllers In Laravel, we can see how useful are the tools that Laravel provides for creating and manipulating API data. Always remember to stay on top of the official Laravel documentation, which is always kept up to date (Laravel Documentation)

Top comments (1)

Collapse
 
danielhe4rt profile image
Daniel Reis

Awesome!