Laravel Handlers

Laravel Handlers

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:

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

and the following controller:

<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Controllers\Controller;

class ShowProfile extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function __invoke($id)
    {
        return view('user.profile', ['user' => User::findOrFail($id)]);
    }
}

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

php 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:

php 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:

composer 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: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Software Engineer Lead (PHP)
Remote
CivicPlus, LLC
Full-time Senior Web Developer
Detroit, MI
Wayne State University
Senior Software Engineer
Sydney, Australia
FoodByUs
Full Stack Engineer
Remote or Medford, Oregon
Empire Medical
Laravel Developer (fulltime - Dutch only)
Netherlands
Qbixx | Webservices
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Senior Quality Assurance Engineer
Remote
Bisnow Media