PHPackages                             coinvestor/larahook - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. coinvestor/larahook

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

coinvestor/larahook
===================

Simple hook engine for Laravel. Forked from esemve/hook

1.4.2(1y ago)226.1k↓30.4%2[1 issues](https://github.com/CoInvestor/larahook/issues)MITPHPPHP &gt;=8.2

Since Oct 9Pushed 1y ago3 watchersCompare

[ Source](https://github.com/CoInvestor/larahook)[ Packagist](https://packagist.org/packages/coinvestor/larahook)[ RSS](/packages/coinvestor-larahook/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (16)Used By (0)

LaraHook - A Hook engine for Laravel
====================================

[](#larahook---a-hook-engine-for-laravel)

This is a maintained fork of the now inactive [esemve/Hook](https://github.com/esemve/Hook) library for laravel 8.

In most cases this library can be used as a drop in replacement, although some changes may require minor updates to your code. Please see [the differences section](#differences-between-this-and-esemvehook) for more information on the changes between this library and `esemve/Hook`

### What is this?

[](#what-is-this)

Hooks allow programmers to make parts of their application open to being modified or adjusted from other locations within the code base. For example allowing an application modify the behavior of your package without them needing directly edit its source code.

### What is a Hook?

[](#what-is-a-hook)

It is similar to an event. A code bounded by a hook runs unless a hook listener catches it and orders that instead of the function in the hook, something else should run. They could be set in an established order, so you are able to make several modifications in the code.

### What is it good for?

[](#what-is-it-good-for)

Example 1: You have a module which displays an editor. This remains the same editor in every case. If you bound the display of the editor in a hook, then you can write a module which can redefine/override this hook, and for example changs the textarea to a ckeditor.

Example 2: You list the users. You can include every line's print in a hook. This way you can write a separate module which could extend this line with an e-mail address print.

Example 3: You save the users' data in a database. If you do it in a hook, you can write a module which could add extra fields to the user model like "first name" or "last name". To do that, you didn't need to modify the code that handles the users, the extension module doesn't need to know the functioning of the main module.

... and so many other things. If you are building a CMS-like system, it will make your life a lot easier.

How do I install it?
====================

[](#how-do-i-install-it)

```
composer require coinvestor/larahook
```

How does it work?
=================

[](#how-does-it-work)

Example code
------------

[](#example-code)

```
$user = new User();
$user = Hook::get('fillUser', [$user], function($user) {
    return $user;
}, true);
```

In this case a fillUser hook is thrown, which receive the $user object as a parameter. If nothing catches it, the internal function, the return $user will run, so nothing happens. But it can be caught by a listener from a provider:

```
Hook::listen('fillUser', function ($callback, $output, $user) {
    $output->profileImage = ProfileImage::getForUser($user->id);
    return $output;
}, 10);
```

The $callback contains the hook's original internal function, so it can be called here.

Multiple listeners could be registered to a hook, so in the $output the listener receives the response of the previously registered listeners of the hook.

THen come the parameters delivered by the hook, in this case the user.

The hook listener above caught the call of the fillUser, extended the received object, and returned it to its original place. After the run of the hook the $user object contains a profileImage variable as well.

Number 10 in the example is the priority. They are executed in an order, so if a number 5 is registered to the fillUser as well, it will run before number 10.

Methods
-------

[](#methods)

### Get

[](#get)

Run a hook and return some data. Listeners for the hook will be triggered and the final result from these will be returned.

```
Hook::get(
    string $hook,                    // Name of the hook to run
    array $params,                   // Array of values to be passed to the listeners on this hook.
    callable $callback,              // Callback method to return default value if no listeners are registered.
    bool $useCallbackAsFirstListener // Should the default callback be run and used as the first $output value
                                     // for the listeners. Defaults to false.
);
```

### Listen

[](#listen)

Listen for the hook and either carry out an action or manipulated the output before it is returned.

```
Hook::listen(
    string $hook,            // Name of the hook to listen on.
    callable $method (       // Callback to execute when hook is run.
        callable $callback,  // Default callback from the `get`. Called as `$callback->call`
        mixed $output,       // Output from previous hook. Will be null unless useCallbackAsFirstListener
                             // is set to true, in which case it will be the default callbacks value.
        mixed $arg1,         // Each value provided to the `get` methods params array, is added to the
        mixed $arg2,         // callbacks arguments in the order they were added.
    )
    int $priority            // Used the control when each listener runs. The higher this value, the later it will run in the list of listeners on the hook.
);
```

Initial output
--------------

[](#initial-output)

By passing `true` as the 4th paramater to the get you can ensure the default callback provided will always run, passing its self as the initial output value.

```
Hook::get('testing', ['Delilah'], function ($testString) {
    return 'Hi ' . $testString;
}, true)

// and later ...

Hook::listen('testing', function ($callback, $output, $name) {
    if ($output === 'Hi Delilah') {
        $output = "{$output}. Whats up!";
    } else {
        $output = "{$output}. Welcome back.";
    }
    return $output; // 'Hi Delilah. Whats up!'
});
```

If there is no listeners, 'Hi Delilah' will be returned.

Usage in blade templates
------------------------

[](#usage-in-blade-templates)

```
@hook('hookName')
```

In this case the hook listener can catch it like this:

```
 Hook::listen('template.hookName', function ($callback, $output, $variables) {
     return view('test.button');
 });
```

In the $variables variable it receives all of the variables that are available for the blade template.

❗ **To listen blade templates you need to listen `template.hookName` instead of just `hookName`!**

Wrap HTML
---------

[](#wrap-html)

```
@hook('hookName', true)
    this content can be modified with dom parsers
    you can inject some html here
@endhook
```

Now the `$output` parameter contains html wrapped by hook component.

```
Hook::listen('template.hookName', function ($callback, $output, $variables) {
    return "$output";
});
```

Stop
----

[](#stop)

```
Hook::stop();
```

Put in a hook listener it stops the running of the other listeners that are registered to this hook.

For testing
-----------

[](#for-testing)

```
Hook::mock('hookName','returnValue');
```

After that the hookName hook will return returnValue as a response.

Artisan
=======

[](#artisan)

```
php artisan hook::list
```

Lists all the active hook listeners.

Differences between this and `esemve/Hook`
==========================================

[](#differences-between-this-and-esemvehook)

- The `$InitialContent` param on `Hook::get` has been replaced by the `useCallbackAsFirstListener` flag. Setting this to `true` will return the result of the default callback as the initial `$output` value.
- Listeners on the same hook at the same priority will no longer overwrite each other. Listerners at the same priority will run in the order you register them.
- Returning a falsey value from a listeners will now return that value directly, rather than causing the default callback to be returned instead.
- Compatibility with laravel 8+.
- `getListeners` can now return listeners for a specified hook. Results will always be an array.
- Caller information now includes file &amp; line numbers.
- Added `removeListener` and `removeListeners` methods.

---

License: MIT

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity71

Established project with proven stability

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~137 days

Recently: every ~241 days

Total

10

Last Release

440d ago

PHP version history (3 changes)1.0.0PHP &gt;=5.6

1.3.0PHP &gt;=8.1

1.4.1PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/e22d6c955042e97d5c5a68cc21b540dc6aa3fdb7f830d56274e51dbb6c10d13e?d=identicon)[bag](/maintainers/bag)

---

Top Contributors

[![esemve](https://avatars.githubusercontent.com/u/7847061?v=4)](https://github.com/esemve "esemve (11 commits)")[![thybag](https://avatars.githubusercontent.com/u/887397?v=4)](https://github.com/thybag "thybag (10 commits)")[![vroomfondle](https://avatars.githubusercontent.com/u/6186584?v=4)](https://github.com/vroomfondle "vroomfondle (10 commits)")[![Xulai](https://avatars.githubusercontent.com/u/5481226?v=4)](https://github.com/Xulai "Xulai (4 commits)")[![fadelgaber](https://avatars.githubusercontent.com/u/40356439?v=4)](https://github.com/fadelgaber "fadelgaber (1 commits)")

---

Tags

hacktoberfestlaravelHOOK

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/coinvestor-larahook/health.svg)

```
[![Health](https://phpackages.com/badges/coinvestor-larahook/health.svg)](https://phpackages.com/packages/coinvestor-larahook)
```

###  Alternatives

[livewire/volt

An elegantly crafted functional API for Laravel Livewire.

4205.3M84](/packages/livewire-volt)[gehrisandro/tailwind-merge-laravel

TailwindMerge for Laravel merges multiple Tailwind CSS classes by automatically resolving conflicts between them

341682.2k18](/packages/gehrisandro-tailwind-merge-laravel)[whitecube/laravel-timezones

Store UTC dates in the database and work with custom timezones in the application.

106106.2k](/packages/whitecube-laravel-timezones)[forxer/laravel-gravatar

A library providing easy gravatar integration in a Laravel project.

4235.6k](/packages/forxer-laravel-gravatar)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2516.7k](/packages/iteks-laravel-enum)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

116.6k](/packages/tomshaw-electricgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
