跳至正文

Package Development ​

Introduction ​

Packages are the primary way to extend Laravel with reusable functionality, from a client for a payment provider to a full admin panel with its own routes, views, and database tables.

General-purpose Go modules, such as an SDK for a payment provider, work in any Go program, and you add them with go get as usual. Laravel packages go further. A Laravel package is an ordinary Go module with a type that implements laravel.Package, and through that type's Register method the package adds settings, services, routes, views, assets, and migrations to every application that installs it.

To illustrate each piece, we'll build github.com/example/inspire, a package that serves inspiring quotes with its own settings, service, routes, middleware, view, and stylesheet.

Creating a package ​

Create a module for your package, then add Laravel to it:

shell
go mod init github.com/example/inspire
go get go.laravel.com

The Register method ​

A package is any type with a Register method that takes a *laravel.Registrar. That method is the entry point for everything your package adds to an application. The quotes package keeps its quotes in a Quotes type, and its New function returns the value that applications install:

go
// Package inspire serves inspiring quotes in a Laravel application.
package inspire

import (
	"math/rand/v2"

	laravel "go.laravel.com"
)

// Quotes are inspiring quotes. Install them with laravel.Options.Packages.
type Quotes struct {
	all []string
}

// New returns the package.
func New() *Quotes {
	return &Quotes{}
}

// Register installs the package in an application.
func (q *Quotes) Register(app *laravel.Registrar) error {
	// Read settings, then add routes, middleware, views, commands, and more...

	return nil
}

// Random returns one of the quotes.
func (q *Quotes) Random() string {
	return q.all[rand.IntN(len(q.all))]
}

Laravel calls each installed package's Register method while the application starts, before it serves requests or runs commands. Your package reads its settings at the top of Register, so it can use them to decide what to add. Returning an error stops the application from starting, which lets your package catch a bad setting at deploy time.

What a package can add ​

Inside Register, the *laravel.Registrar has a method for each of the options that an application sets in bootstrap/app.go:

MethodAddsCounterpart in laravel.Options
Env(), Config()Nothing. They return the environment to read your settings from, and the application's final configuration.Env, Config
ServicesThe package's services, which its jobs and the application's handlers find through the contextServices
Web, API, BareRoutes in the web or API group, or bare routes without a prefix or group middlewareRoutes.Web, Routes.API, Routes.Bare
ChannelsWho may subscribe to the package's broadcast channelsRoutes.Channels
MiddlewareGlobal, web, and API middlewareMiddleware
Views, ViewFuncsView namespaces, and functions every view may callViews, ViewFuncs
AssetsEmbedded assets served at /vendor/<namespace>/None
Migrations, SeedersMigrations that migrate runs, and seeders that db:seed runsMigrations, Seeders
CommandsConsole commandsCommands
Jobs, Workflows, ScheduleQueued jobs and scheduled tasks, and durable workflowsJobs, Workflows, Schedule
ListenersEvent listenersListeners
TicksTicks that repeat inside each server processTicks
FeaturesFeature flagsFeatures
ErrorsCustom error reporting and renderingErrors
LogHandlerA log handler that sees every recordLogHandler
CacheStore, SessionStore, FeatureStore, WorkflowStoreCustom stores, such as a cache store or session store, that the application selects by nameCacheStores, SessionStores, FeatureStore, WorkflowStore
Mailer, QueueConnection, NotificationChannels, SlackActionsA mailer, a queue connection, notification channels, or Slack actionsMailers, QueueConnections, NotificationChannels, SlackActions
SearchEngineA search engine that SEARCH_ENGINE selectsSearchEngines

When your package adds a store, give it a name of its own, such as vault. An application then selects it with the same setting that selects one of Laravel's stores, such as CACHE_STORE=vault.

Installing a package ​

Installing a Laravel package into an application takes two explicit steps: adding the module to your application, and listing the package in bootstrap/app.go. Listing packages explicitly keeps your application's startup transparent, and lets you see every package your application loads in one place.

Adding the module ​

From your application's root directory, add the package with go get:

shell
go get github.com/example/inspire

Go resolves the latest version and adds the module to the require block in your go.mod:

text
require github.com/example/inspire v0.1.0

When you develop a package alongside an application, you may point Go at your local checkout instead by creating a workspace with go work init . ../inspire in the application's directory.

Listing the package ​

Adding the module makes its types available to import, but it doesn't add anything to your application yet. To activate the package's settings, services, routes, views, middleware, and migrations, add the package to Packages in bootstrap/app.go:

go
package bootstrap

import (
	"github.com/example/inspire"
	laravel "go.laravel.com"
)

func Options() laravel.Options {
	return laravel.Options{
		Packages: []laravel.Package{inspire.New()},
		// ...
	}
}

Laravel registers packages in the order you list them, so a package listed later appends its middleware after an earlier package's. Your application's own options, such as Middleware, Commands, and Errors, always apply after every package, so your application may change or remove anything a package adds. Your tests build their application from the same bootstrap.Options, so they install the package too.

Configuration ​

Most packages expose settings that each application chooses, such as an API key or whether a feature is on. Give your package a Config type, and fill it at the top of Register from app.Env(). That's the environment Laravel reads its own settings from, so your package's settings come from .env on a developer's machine and from the process's environment on a server:

go
// Config is the package's settings.
type Config struct {
	// Header adds an X-Inspiration header to every web response.
	// INSPIRE_HEADER sets it, and it is on unless set.
	Header bool
	// Quotes are added to the built-in ones. INSPIRE_QUOTES sets them,
	// separated by |.
	Quotes []string
}

func (q *Quotes) Register(app *laravel.Registrar) error {
	env := app.Env()
	cfg := Config{
		Header: env.Bool("INSPIRE_HEADER", true),
		Quotes: strings.FieldsFunc(env.String("INSPIRE_QUOTES", ""), func(c rune) bool {
			return c == '|'
		}),
	}
	q.all = slices.Concat(builtIn, cfg.Quotes)

	// ...

	return nil
}

Here, builtIn is the package's own list of quotes. If a variable holds a value that doesn't parse, such as INSPIRE_HEADER=maybe, the application refuses to start, and its error lists your package's setting beside any of Laravel's own settings that are invalid.

Sometimes an application needs to set a value in code instead of in its environment, such as adding a quote of its own. To support that, let New take functions that change the settings after your package reads them from the environment:

go
// Quotes are inspiring quotes. Install them with laravel.Options.Packages.
type Quotes struct {
	configure []func(cfg *Config)
	all       []string
}

// New returns the package. Each configure function changes the settings
// that the package read from the environment.
func New(configure ...func(cfg *Config)) *Quotes {
	return &Quotes{configure: configure}
}

In Register, call each of those functions after you read the environment and before you use the settings:

go
for _, change := range q.configure {
	change(&cfg)
}
q.all = slices.Concat(builtIn, cfg.Quotes)

An application that installs your package then passes its change to inspire.New in bootstrap/app.go, and every other setting keeps the value your package read from the environment:

go
Packages: []laravel.Package{
	inspire.New(func(cfg *inspire.Config) {
		cfg.Quotes = append(cfg.Quotes, "Ship it. - Taylor")
	}),
},

Services ​

The *Quotes value that New returns is also your package's service, because it holds the quotes. Your package's routes may use that value directly in Register, but its jobs can't, because a worker builds each job from the data that was queued. Register the value with app.Services, and give your package a From function that returns the value from a context:

go
func (q *Quotes) Register(app *laravel.Registrar) error {
	app.Services(q)

	// ...

	return nil
}

// From returns the Quotes that ctx's application installed.
func From(ctx context.Context) *Quotes {
	return laravel.ServicesOf[*Quotes](ctx)
}

laravel.ServicesOf looks up a service by its type in the application that the context carries, so register a type that belongs to your package. If two packages register services of the same type, the application refuses to start. Your jobs may then reach the quotes from the ctx they receive, and an application's handlers may reach them from the request:

go
quote := inspire.From(r).Random()

From panics if the application didn't list your package in bootstrap.Options, because that mistake is in the application's setup, not in any one request.

Routes ​

Add routes to the web group with app.Web, or to the API group under /api with app.API. For endpoints that shouldn't carry the /api prefix or run the web group's session and CSRF middleware, such as a payment provider's webhook, use app.Bare. Each method takes a function shaped like the ones in an application's route files, which receives the router and the application's configuration, and the routes run the middleware of the group you add them to:

go
func (q *Quotes) Register(app *laravel.Registrar) error {
	app.Web(func(route *routing.Router, cfg *config.Config) {
		route.Get("/inspire", q.Show).Name("inspire")
		route.Get("/inspire/page", q.Page).Name("inspire.page")
	})

	return nil
}

// Show answers GET /inspire with a random quote.
func (q *Quotes) Show(r *web.Request) *web.Response {
	return web.Text(q.Random())
}

Start your routes' names with your package's name, such as inspire.page, so they don't collide with the application's own. Applications link to package routes by name, such as urls.Route(r, "inspire.page").

If your package broadcasts on private or presence channels, such as a billing package that pushes each invoice's status to its owner, authorize those channels with app.Channels. It takes the same kind of function as an application's Routes.Channels. Laravel matches your patterns before the application's, so start each pattern with your package's name:

go
app.Channels(func(channel *routing.Channels) {
	channel.Private("billing.invoices.{invoice}", b.AuthorizeInvoice)
})

Middleware ​

Your package may add global, web, or API middleware with app.Middleware, which receives the same *laravel.Middleware as an application's Middleware option. Because your package reads its settings at the top of Register, you may attach AddInspiration only when Header is on, instead of checking the setting on every request:

go
if cfg.Header {
	app.Middleware(func(m *laravel.Middleware) {
		m.Web.Append(AddInspiration{Quotes: q})
	})
}

Here, AddInspiration is the package's middleware, which adds a quote to each response's headers. Applications run their own Middleware option after every package, so an application may also remove a package's middleware in bootstrap/app.go with m.Remove(inspire.AddInspiration{}).

Views ​

Because a deployed Laravel application is often a single binary without your package's source files beside it, embed your package's views with //go:embed and register them under a namespace with app.Views:

go
//go:embed views
var views embed.FS

func (q *Quotes) Register(app *laravel.Registrar) error {
	files, err := fs.Sub(views, "views")
	if err != nil {
		return err
	}
	app.Views("inspire", files)

	return nil
}

Package views are html/template files, and they may call every one of Laravel's helpers, such as csrfField, route, and vendorAsset:

html
<!-- views/quote.html -->

<link rel="stylesheet" href="{{vendorAsset "inspire" "inspire.css"}}">
<blockquote>{{.}}</blockquote>
<a href="{{route "inspire.page"}}">Another</a>

Render a namespaced view by its namespace and name, such as inspire::quote:

go
// Page answers GET /inspire/page with a quote on a page.
func (q *Quotes) Page(r *web.Request) *web.Response {
	return web.View("inspire::quote", q.Random())
}

Applications may override any package view by placing a file at resources/views/vendor/inspire/quote.html. To start from a copy of your view, a developer runs laravel vendor:publish inspire quote. Document the data each of your views receives, so an application's copy keeps working.

Assets ​

Embed stylesheets, scripts, and images with //go:embed and register them with app.Assets. Laravel serves them at /vendor/<namespace>/<path>:

go
//go:embed public
var public embed.FS

func (q *Quotes) Register(app *laravel.Registrar) error {
	files, err := fs.Sub(public, "public")
	if err != nil {
		return err
	}
	app.Assets("inspire", files)

	return nil
}

Reference package assets with the vendorAsset function in views:

html
<link rel="stylesheet" href="{{vendorAsset "inspire" "inspire.css"}}">

In Go code, such as a handler, call view.VendorAsset(r, "inspire", "inspire.css") instead. Laravel appends a hash of the file's contents to the URL (/vendor/inspire/inspire.css?id=34b6aba934cd2bfe) for cache busting. Applications may override any asset by placing a replacement file in public/vendor/inspire/.

Building assets with Vite ​

If your package compiles JavaScript or CSS with Vite, such as an admin dashboard's scripts, build the assets before you release, commit the built directory, and embed it with //go:embed so applications that install your package don't need Node or Vite.

For a single entry point, this Vite 8 configuration outputs file names that stay the same from one build to the next (dist/app.js and dist/style.css):

js
import { defineConfig } from 'vite';

export default defineConfig({
	base: '/vendor/dashboard/',
	publicDir: false,
	build: {
		outDir: 'dist',
		cssCodeSplit: false,
		rolldownOptions: {
			input: 'resources/js/app.js',
			output: {
				entryFileNames: 'app.js',
				assetFileNames: '[name][extname]',
				codeSplitting: false,
			},
		},
	},
});

Import your CSS from the JavaScript entry point (import '../css/app.css') and set base to /vendor/<namespace>/ so relative font and image URLs resolve. Register the build directory and link the assets from your views:

go
//go:embed dist
var dist embed.FS

func (d *Dashboard) Register(app *laravel.Registrar) error {
	files, err := fs.Sub(dist, "dist")
	if err != nil {
		return err
	}
	app.Assets("dashboard", files)

	return nil
}
html
<link rel="stylesheet" href="{{vendorAsset "dashboard" "style.css"}}">
<script type="module" src="{{vendorAsset "dashboard" "app.js"}}"></script>

An application downloads your module from its repository, so it receives only the files you commit. Commit dist even though built files usually belong in .gitignore, and rebuild it before you tag each release:

shell
npx vite build
git add dist
git commit -m "Build assets"
git tag v0.2.0

Migrations ​

Packages that store database tables, such as a billing package's invoices, can ship migrations. Keep them in a migrations package inside your module. List them in an All variable, as an application's database/migrations package does, and register them with app.Migrations:

go
app.Migrations(migrations.All...)

Running migrate in an application executes package and application migrations together in name order, and laraveltest.RefreshDatabase builds them into the test database too. Start each migration's name with the time you created it, as make:migration does, such as 2026_11_11_090000_create_invoices_table, so it runs after the tables it depends on.

Seeders ​

If your tables need rows before the application can work, such as the plans a billing package offers, ship a seeder that writes them, and register it with app.Seeders:

go
app.Seeders(laravel.Seeder{Name: "billing:plans", Run: seedPlans})

db:seed runs your seeders before the application's own, so the application's seeders may use the rows yours wrote. Start each seeder's name with your package's name, as billing:plans does. An application may replace one of your seeders by adding its own seeder with the same name.

Commands and scheduled tasks ​

Packages can register their own console commands, so applications gain new commands as soon as they install the package. A command's Run method receives a ctx that carries the application, so the command reads the same configuration and database as your routes. For anything else the command needs from your package, such as the quotes, give the command a field:

go
// ListQuotes lists every inspiring quote.
type ListQuotes struct {
	quotes *Quotes
}

func (*ListQuotes) Name() string        { return "inspire:list" }
func (*ListQuotes) Description() string { return "List every inspiring quote" }

func (l *ListQuotes) Run(ctx context.Context, c *console.Console) error {
	for _, quote := range l.quotes.all {
		c.Line(quote)
	}

	return nil
}

To register the command, call app.Commands in Register with the package's own value in that field:

go
app.Commands(&ListQuotes{quotes: q})

Start your commands' names with your package's name, as inspire:list does, so laravel list shows them together. If an application defines a command with the same name, the application's command replaces the package's.

If your package needs to run recurring work, such as emailing a quote of the day to its subscribers each morning, write the work as a queued job and schedule it with app.Schedule, which takes the same kind of function as an application's schedule. Register a value of the job's type with app.Jobs too, so the application's workers know how to run it. If you leave the type out, dispatching the job returns an error:

go
// SendDailyQuote emails the quote of the day to subscribers.
type SendDailyQuote struct{}

func (SendDailyQuote) Handle(ctx context.Context) error {
	quote := From(ctx).Random()

	// Email the quote...
	_ = quote

	return nil
}

func (q *Quotes) Register(app *laravel.Registrar) error {
	app.Services(q)
	app.Jobs(SendDailyQuote{})
	app.Schedule(func(ctx context.Context, s *schedule.Schedule) {
		s.Job(SendDailyQuote{}).DailyAt("08:00")
	})

	return nil
}

Scheduled package tasks run automatically whenever the application runs its scheduler, and Laravel defines them before the application's own.

Feature flags ​

To roll out a change to your package gradually, such as a new quote picker, define a feature flag for it and register it with app.Features:

go
var NewPicker = feature.Define(
	"inspire.new_picker",
	func(ctx context.Context, _ feature.Global) (bool, error) {
		return false, nil
	},
)

func (q *Quotes) Register(app *laravel.Registrar) error {
	app.Features(NewPicker)

	return nil
}

Your handlers check the flag with feature.Active(r, NewPicker), as an application's handlers do. Start each flag's name with your package's name, because two flags with the same name stop the application from starting.

Errors ​

Some of your package's errors are the user's problem rather than a bug, such as a card that the customer's bank declined, which should reach the browser as a 402 rather than a 500. Give the error type a StatusCode method so applications don't have to map each error themselves:

go
// CardDeclined is a payment the customer's bank refused.
type CardDeclined struct{}

func (CardDeclined) Error() string { return "The card was declined." }

func (CardDeclined) StatusCode() int { return http.StatusPaymentRequired }

For additional error handling, pass a web.Errors to app.Errors in Register. It takes the same fields as an application's Errors option. For example, a billing package might stop reporting expected declines, keep card numbers out of old input, and answer an API client whose card was declined with JSON that says why:

go
func (b *Billing) Register(app *laravel.Registrar) error {
	app.Errors(web.Errors{
		Ignore:    func(err error) bool { return errors.Is(err, CardDeclined{}) },
		DontFlash: []string{"card.number", "card.cvc"},
		Render: func(r *web.Request, err error) *web.Response {
			if !errors.Is(err, CardDeclined{}) || !r.ExpectsJSON() {
				return nil
			}

			body := map[string]string{
				"error":   "card_declined",
				"message": err.Error(),
			}

			return web.JSON(body).WithStatus(http.StatusPaymentRequired)
		},
	})

	return nil
}

Applications apply their own Errors option after every package's, so an application's Render runs first and takes precedence over a package's for the same error. When the application's Render returns nil, Laravel tries each package's Render in turn.

Logging ​

Packages can send the application's logs somewhere of their own, such as an error tracker, through app.LogHandler. It takes a function that receives the application's slog handler and returns a handler that sees every record first. Pass each record on to the application's handler as well, so the application's log channels still receive it. slog.NewMultiHandler sends each record to both:

go
func (t *Tracker) Register(app *laravel.Registrar) error {
	if t.key == "" {
		return nil
	}

	app.LogHandler(func(next slog.Handler) slog.Handler {
		return slog.NewMultiHandler(next, t.Handler(slog.LevelError))
	})

	return nil
}

Here, t.Handler stands for the package's own slog.Handler, which sends records at or above the given level to the tracker. Your handler receives each record with the context it was logged with, so web.RequestID(ctx) returns the ID of the request that logged the record. To learn which records Laravel logs, such as a line for each request, check out the logging guide.

Checks at startup ​

Returning an error from Register prevents the application from starting, catching misconfigurations at deploy time rather than on the first request. For example, a quote with a line break in it can't be sent in a header, so when its header is on, the quotes package checks every quote at the end of Register:

go
if !cfg.Header {
	return nil
}

i := slices.IndexFunc(q.all, func(quote string) bool {
	return strings.ContainsFunc(quote, unicode.IsControl)
})
if i >= 0 {
	return fmt.Errorf(
		"the quote %q can't be sent in a header: turn off INSPIRE_HEADER, or remove the quote",
		q.all[i],
	)
}

return nil

The startup error names your package's type, so developers can immediately identify the failing package.

Laravel may call Register more than once on the same value, such as when a test looks up an application's migrations before it builds the application. Make each call set your package up identically by assigning its settings and lists in Register, as q.all = slices.Concat(...) does, rather than appending to what an earlier call left behind.

Testing packages ​

Place your package's tests in _test.go files beside its code, such as inspire_test.go, in an inspire_test package. Because Go compiles an _test package separately, your tests exercise your package through its exported API, as an application will.

Unlike an application, a package doesn't have a bootstrap/app.go or tests/tests.go. Extract a helper function, such as newApp, that passes laravel.Options with your package installed to laraveltest.New and accepts variadic laraveltest.Option values so individual tests can override settings:

go
package inspire_test

import (
	"testing"

	laravel "go.laravel.com"
	"go.laravel.com/laraveltest"

	"github.com/example/inspire"
)

func newApp(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
	t.Helper()

	return laraveltest.New(t, laravel.Options{
		Packages: []laravel.Package{inspire.New()},
	}, with...)
}

func TestTheRouteAnswersWithAQuote(t *testing.T) {
	client := newApp(t)

	client.Get("/inspire").AssertOK().AssertHeaderPresent("X-Inspiration")
	client.Get("/vendor/inspire/inspire.css").AssertOK()
}

Extract the helper, not a shared application instance. Each call to newApp builds a fresh application with its own sessions, cache, fakes, clock, and configuration, so tests can't affect one another and may run in parallel with t.Parallel(). Calling t.Helper() makes Go report setup failures on the calling test's line instead of inside newApp.

As your test suite grows across multiple files, move newApp into a file such as helpers_test.go in package inspire_test so every *_test.go file in the package can call it. If your module has several Go packages that all need the same test application, place the helper in an internal/testapp package.

When every test in your package needs shared setup, such as a database driver and laraveltest.RefreshDatabase for package migrations, default environment variables, or a host route to verify package middleware, add that setup inside newApp. Prepend your shared laraveltest.Option values before with... so options passed by a single test override the defaults:

go
// helpers_test.go
package inspire_test

import (
	"testing"

	laravel "go.laravel.com"
	"go.laravel.com/config"
	"go.laravel.com/db"
	"go.laravel.com/db/sqlite"
	"go.laravel.com/laraveltest"
	"go.laravel.com/routing"
	"go.laravel.com/web"

	"github.com/example/inspire"
)

func newApp(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
	t.Helper()

	with = append([]laraveltest.Option{
		laraveltest.Env(map[string]string{"DATABASE_URL": "sqlite::memory:"}),
		laraveltest.RefreshDatabase,
	}, with...)

	return laraveltest.New(t, laravel.Options{
		Drivers:  []db.Driver{sqlite.Driver},
		Packages: []laravel.Package{inspire.New()},
		Routes: laravel.Routes{
			Web: func(route *routing.Router, _ *config.Config) {
				route.Get("/host", func(r *web.Request) *web.Response {
					return web.Text("ok")
				})
			},
		},
	}, with...)
}

When a package repository has no .env file, your package's settings keep their fallbacks. When a single test needs a setting changed, pass laraveltest.Env to newApp:

go
func TestTurningOffTheHeaderSkipsTheMiddleware(t *testing.T) {
	client := newApp(t, laraveltest.Env(map[string]string{"INSPIRE_HEADER": "off"}))

	client.Get("/inspire").AssertOK().AssertHeaderMissing("X-Inspiration")
}

If a single test needs to adjust laravel.Options directly, such as checking that a consuming application can remove your package's middleware, pass a laraveltest.OptionFunc to newApp:

go
func TestAnApplicationCanRemoveTheMiddleware(t *testing.T) {
	client := newApp(t, laraveltest.OptionFunc(func(_ testing.TB, options *laravel.Options) {
		options.Middleware = func(m *laravel.Middleware, _ *config.Config) {
			m.Remove(inspire.AddInspiration{})
		}
	}))

	client.Get("/inspire").AssertOK().AssertHeaderMissing("X-Inspiration")
}

Because laraveltest.New fails the test when the application can't start, test a startup check by calling laravel.New yourself and asserting that it returns an error:

go
func TestAQuoteWithALineBreakStopsTheApplication(t *testing.T) {
	_, err := laravel.New(laravel.Options{
		Config: laraveltest.Config(),
		Env:    config.NewEnv(nil),
		Packages: []laravel.Package{
			inspire.New(func(cfg *inspire.Config) {
				cfg.Quotes = append(cfg.Quotes, "Line one\nLine two")
			}),
		},
	})

	if err == nil || !strings.Contains(err.Error(), "can't be sent in a header") {
		t.Fatalf("got %v, want an error about the header", err)
	}
}

Run your package's tests with go test ./.... To explore additional requests, assertions, and fakes the test client offers, check out the testing guide.