A Laravel Package helper for Laravel Packages

v1.6.1 2022-04-11 02:43 UTC

This package is auto-updated.

Last update: 2023-01-26 02:03:19 UTC


Latest Version on Packagist Latest stable test run Codecov coverage Maintainability Sonarcloud Status Laravel Octane Compatibility

A Laravel Package helper for Laravel Packages.

public function boot()
    $this->withSchedule(fn($schedule) => $schedule->command('inspire')->hourly());

Become a sponsor

Your support allows me to keep this package free, up-to-date and maintainable. Alternatively, you can spread the word!


  • PHP 8.0 or later.
  • Laravel 9.x or later.


Require this package into your project using Composer:

composer require laragear/meta

This package contains traits and classes to ease package development and package testing.

All classes and traits have been marked with the @internal PHPDoc tag. This will avoid some IDE to take into account these structural files into autocompletion / intellisense.


The Discoverer class is a builder that allows discovering classes under a given path. It contains various fluent methods to filter the classes to discover, like methods, properties, interfaces and traits, among others.

You can use this class, let's make an example about a package that needs to list several classes inside App\Scoreboards, that include at least one method starting with handle, like handleAwayTeam().

use Laragear\Meta\Discover;
use Vendor\Package\Facades\Scoreboard;

$classes = Discover::in('Scoreboards')->withMethod('handle*')->all();


By default, it always starts from the Application root path and namespace, which are app and App respectively. If you need to, you can change both independently using atNamespace().

use Laragear\Meta\Discover;

$classes = Discover::in('Scoreboards')->atNamespace('Score')->withMethod('handle*')->all();

In any case, the discovered classes are returned as a Collection instance, with instances of ReflectionClass to further filter the list to your needs. For example, we will filter all those scoreboards that have the property hidden.

use Laragear\Meta\Discover;
use ReflectionClass;

Discover::in('Events')->all()->filter(function (ReflectionClass $class) {
    return $class->hasProperty('hidden');

The discovered classes must be always PSR-4 autoloaded.

Boot Helpers

The BootHelpers trait adds some convenient Service Provider methods at boot time to add rules, middleware, listeners, and subscribers.

public function boot()
    // Extends a service manager with a custom driver
    $this->withDriver('cache', 'nfs', fn () => new NfsCacheDriver());
    // Registers a validation rule.
    $this->withValidationRule('age', fn($attribute, $value) => $value > 18, 'You are too young!', true);
    // Registers a middleware using fluent methods.
    // Registers a listener for a given event.
    $this->withListener('birthday', GreetOnBirthday::class);
    // Registers a subscriber for many events.
    // Registers one or many scheduled jobs using a callback.
    $this->withSchedule(function ($schedule) {

Middleware declaration

When using withMiddleware() you will receive a MiddlewareDeclaration object with convenient methods to register the middleware globally or inside a group, set it as first/last in the global priority stack, and register an alias for it.

public function boot()
    $declaration = $this->withMiddleware(OnlyAdults::class);
    // Make it a shared instance.
    // Set an alias
    // Puts it inside a middleware group.
    // Sets the middleware in the global stack.
    // Makes the middleware run first or last in the priority stack.


Testing the Service Provider

The InteractsWithServiceProvider allows to quickly test if the Service Provider of your package has registered all the needed bits of code into the Service Container.

use Orchestra\Testbench\TestCase
use Laragear\Meta\Testing\InteractsWithServiceProvider;

class ServiceProviderTest extends TestCase
    use InteractsWithServiceProvider;
    public function test_is_registered_as_singleton(): void

The available assertions are in this table:

assertServices() assertViews() assertMiddlewareInGroup()
assertSingletons() assertBladeComponent() assertGateHasPolicy()
assertConfigMerged() assertBladeDirectives() assertGateHasPolicy()
assertPublishes() assertValidationRules() assertScheduledTask()
assertPublishesMigrations() assertMiddlewareAlias() assertScheduledTaskRunsAt()
assertTranslations() assertGlobalMiddleware() assertMacro()

Service Helpers

The InteractsWithServices trait includes helpers to retrieve services from the Service Container and do quick things.

public function test_something_important(): void
    // Get a service from the Service Container, optionally run over a callback.
    $cache = $this->service('cache', fn ($cache) => $cache->set('foo', 'bar', 30));
    // Run a service once and forgets it, while running a callback over it.
    $compiler = $this->serviceOnce('blade.compiler', fn($compiler) => $compiler->check('cool'));
    // Executes a callback over a REAL service when already mocked.
    $this->unmock('files', function ($files): void {
        $files->copyDirectory('foo', 'bar');


This meta package includes a InteractsWithValidation trait, that assert if a rule passes or fails using minimal data. This is useful when creating validation rules and testing them without too much boilerplate.

public function test_validation_rule(): void
    // Assert the validation rule passes.
    $this->assertValidationPasses(['test' => 'foo'],['test' => 'my_rule']);
    // Assert the validation rule fails.
    $this->assertValidationFails(['test' => 'bar'],['test' => 'my_rule']);


You can test a middleware easily using the InteractsWithMiddleware trait and its middleware() method. It creates an on-demand route for the given path before sending a test Request to it, so there is no need to register a route.

use Illuminate\Http\Request;
use Vendor\Package\Http\Middleware\MyMiddleware;
use Laragear\Meta\Testing\Http\Middleware\InteractsWithMiddleware;

public function test_middleware(): void
    $response = $this->middleware(MyMiddleware::class)->using(function (Request $request) {
        // ...
    })->post('test', ['foo' => 'bar']);

It proxies all MakesHttpRequest trait methods, like get() or withUnencryptedCookie(), so you can get creative with testing your middleware.

$this->middleware(MyMiddleware::class, 'test_argument')
    ->post('test/route', ['foo' => 'bar'])

Form Request

You can test a Form Request if it passes authorization an validation using different data using the InteractsWithFormRequests trait. The formRequest() requires the Form Request class, and an array with the data to include in the request, to test in isolation.

public function test_form_request()
    $this->formRequest(MyFormRequest::class, ['foo' => 'bar'])->assertOk();


To check if a policy or gate works appropriately, use the InteractsWithAuthorization trait to check whether a user can or cannot be authorized to a given action.

public function test_authorization()
    $this->assertUserCan($this->user, 'doSomething');


The InteractsWithCast trait allows to quickly test if a cast sets values from an attribute appropriately, and can return a given value from an attribute value. It also supports checking on multiple attributes at a time.

public function test_cast()
        ->assertCastFrom(null, new Cast)
        ->assertCastTo('{"foo":"bar"}', new Cast(['foo' => 'bar']));

Builder extender

The ExtendsBuilder trait allows a Global Scope to extend the instance of the Eloquent Builder with new methods. Simply add public static methods in the scope that receive a Builder instance, and optional parameters if you deem so.

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Laragear\Meta\Database\Eloquent\ExtendsBuilder;

class Cars implements Scope
    use ExtendsBuilder;
    public function apply(Builder $builder, Model $model)
        // ...
    public static function whereAvailable(Builder $builder)
        return $builder->where('available_at', '>', now());
    public static function whereColor(Builder $builder, string $color)
        return $builder->where('base_color', $color);

If you need the model being queried, you can always use getModel() over the Eloquent Builder instance.

Command Helpers

This meta package includes command helpers for modifying the environment file, other files, confirm on production, and operate with stub files.

Trait Description
WithEnvironmentFile Retrieve and replace environment file keys.
WithProductionConfirmation Confirm an action on production environments.
WithStubs Copy custom stubs to a destination, while replacing custom strings.

Laravel Octane compatibility

  • There are no singletons using a stale application instance.
  • There are no singletons using a stale config instance.
  • There are no singletons using a stale request instance.
  • ExtendsBuilder only initializes its static property once per Scope.

There should be no problems using this package with Laravel Octane.


If you discover any security related issues, please email instead of using the issue tracker.


This specific package version is licensed under the terms of the MIT License, at time of publishing.

Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC.