Laravel Handlers

News

July 23rd, 2018

laravel-handlers.jpg

Laravel Handlers is a package by Ilya Sakovich for creating single-action request handlers. The idea of a request handler is a single-action controller which means that a unique class handles each request.

Laravel supports the idea of a single-action controller via the __invoke() magic method and outlined in the controllers documentation:

1Route::get('user/{id}', 'ShowProfile');

and the following controller:

1<?php
2
3namespace App\Http\Controllers;
4
5use App\User;
6use App\Http\Controllers\Controller;
7
8class ShowProfile extends Controller
9{
10 /**
11 * Show the profile for the given user.
12 *
13 * @param int $id
14 * @return Response
15 */
16 public function __invoke($id)
17 {
18 return view('user.profile', ['user' => User::findOrFail($id)]);
19 }
20}

With this package, you can create these controllers with the make:handler command:

1php artisan make:handler ShowProfile

If you want to create a request handler for each resource action (index, show, create, store, edit, etc.) you can use the --resource flag:

1php artisan make:handler Post --resource

The resource flag will create the following single-action controller classes:

  • IndexPost
  • ShowPost
  • CreatePost
  • StorePost
  • EditPost
  • UpdatePost
  • DestroyPost

Adding the --api flag will only include the necessary API actions, and exclude create and edit.

The single-action controller is beneficial to understand, and I tend to use them for actions that don’t match one of the REST verbs. A single-action controller for non-REST verbs is an excellent way to communicate that this is a stand-alone controller.

You might even like this approach for all controllers so experiment with them and see how you feel about how much you use them.

Learn More

You can install this package in your project with the following composer package:

1composer require hivokas/laravel-handlers

You can learn more about this package and how to configure your route files to accommodate handler routes on GitHub at hivokas/laravel-handlers.

You can find Ilya on GitHub at hivokas. Thanks for your contribution to the Laravel community!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.