A Laravel Trait for Hooking Before and After Method Calls
claudye/laravel-hooks is a Laravel package for a laravel trait for hooking before and after method calls.
It currently has 9 GitHub stars and 1.046 downloads on Packagist (latest version 1.1.1).
Install it with composer require claudye/laravel-hooks.
Discover more Laravel packages by claudye
or browse all Laravel packages to compare alternatives.
Last updated
Laravel Hooks is a Laravel trait that allows you to register hooks (callbacks) before and after calling specified methods in a Laravel controllers. This helps you modify or extend the behavior of methods without altering their core logic.
useHooks method.You can install this package via Composer. Make sure your Laravel version is 7.x or higher (up to 11.x supported).
Run the following command to install the package:
composer require claudye/laravel-hooks
Here's an example of how to use the HasControllerHooks trait in your Laravel controller or class:
namespace App\Http\Controllers;
use LaravelHooks\Traits\HasControllerHooks;
use Illuminate\Http\Request;
class ExampleController extends Controller
{
use HasControllerHooks;
public function index(Request $request)
{
// Your logic here.
return [
"users" => $this->queryBuilder->all()
];
}
public function show(Request $request)
{
// Your logic here.
return [
"user" => $user
];
}
/**
* Defines hooks for methods in the controller.
*/
public function useHooks()
{
// Register a before hook for the 'index' method
$this->beforeCalling(['index', 'show'], function ($request,...$parameters, $method) {
$this->queryBuilder->filters($request->all());
logger('Before calling index method');
});
// Register an after hook for the 'index' method
$this->afterCalling(['index',"show","edit"], function ($request, $result,...$parameters, $method) {
// Modify the result after the 'index' method is called
logger('After calling index method');
event(new SomeEvent($result))
return response()->json([
'data'=>$result
]);
});
// You can add other hooks as necessary.
}
}
You can modify the controller instance itself before a method is executed, which is particularly useful when working with dependency injection.
Example:
$this->beforeCalling(['store',"update","delete"], function ($parameter1, $parameter2,...$methodName) {
// Modify the controller instance before executing 'store' method
$this->someService = app(SomeService::class)->init();
$parameter1->modify();
});
If a method does not exist when trying to call it via the callAction method, a BadMethodCallException will be thrown, providing more clarity during development.
This package is open-source software licensed under the MIT License.