laravel

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 104 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Laravel Logo

About Laravel

Note: This repository contains the core code of the Laravel for Go framework. If you want to build an application using Laravel for Go, visit the main Laravel for Go repository.

Laravel for Go is a full-stack web framework built for ambitious applications. We believe building software should be a productive, rewarding experience from day one. Laravel gives you everything you need out of the box by handling the foundational pieces of modern web development, such as:

Laravel is accessible, yet powerful, providing tools needed for large, robust applications. A superb combination of simplicity, elegance, and innovation gives you a complete toolset required to build any application with which you are tasked.

Learning Laravel

Laravel for Go has extensive and thorough documentation, making it a breeze to get started with the framework. If you're new to Laravel for Go, start with the installation guide.

Code of Conduct

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

License

The Laravel for Go framework is open-sourced software licensed under the MIT license.

Documentation

Overview

Package laravel builds and runs a Laravel application.

An App implements http.Handler, combining your routes, Laravel's default middleware, and your configuration. Describe the application in Options and pass it to Run from main:

func main() {
	laravel.Run(laravel.Options{
		Routes: laravel.Routes{Web: routes.Web, API: routes.API, Health: "/up"},
	})
}

Run parses the command line and executes the requested command, defaulting to serve when none is given, alongside built-in commands such as migrate and any custom Command values you register. Because App is an http.Handler, you can also construct one with New and pass it directly to http.Server or net/http/httptest.

Index

Constants

View Source
const Version = version.Version

Version is the current framework release version.

Variables

This section is empty.

Functions

func Background

func Background(ctx context.Context, work func(ctx context.Context) error)

Background runs work in a separate goroutine and returns immediately, for non-critical tasks that do not need to finish before the caller returns, such as notifying a webhook after a command completes. Pass the scoped context from a command, job, or listener; HTTP handlers should call web.Request.Background instead:

laravel.Background(ctx, func(ctx context.Context) error {
	return webhooks.PostPublished(ctx, post.ID)
})

When called inside a database transaction, Background waits until the outermost transaction commits so work can read committed rows, and discards work if the transaction rolls back. The goroutine's context preserves values from ctx while dropping its cancellation and transaction. Laravel logs any error returned by work and recovers and logs panics.

The serve command and every CLI command wait for in-flight background work up to SERVER_SHUTDOWN_TIMEOUT before exiting, canceling any remaining work with web.ErrShutdown. Background work is not durable: Laravel does not retry failures, and a process crash loses in-flight tasks. Background panics when ctx does not carry an application scope, such as context.Background.

func BuildServices

func BuildServices[S any](build func(env *config.Env, app *App) S) func(env *config.Env, app *App) any

BuildServices adapts a typed services constructor for Options.Services. The application stores a pointer to the value that build returns:

Services: laravel.BuildServices(services.New),

func CallSeeder

func CallSeeder(ctx context.Context, name string) error

CallSeeder runs the named seeder from inside another seeder using ctx so both share the same seeding transaction:

func comments(ctx context.Context) error {
	if err := laravel.CallSeeder(ctx, "posts"); err != nil {
		return err
	}

	// Add comments to the posts...
}

Each seeder runs at most once per seeding run, even when invoked by both db:seed and CallSeeder, so seeders can declare dependencies safely without inserting duplicate rows. CallSeeder returns an error if no seeder has the given name, and panics when ctx is not from an active seeding run.

func IsDownForMaintenance

func IsDownForMaintenance(ctx context.Context) bool

IsDownForMaintenance reports whether the application attached to ctx is in maintenance mode, started by the down command and ended by the up command:

if laravel.IsDownForMaintenance(ctx) {
	return nil
}

It panics when ctx does not carry an application scope.

func Migrations

func Migrations(options Options) ([]db.Migration, error)

Migrations returns all database migrations for options, combining package migrations with Options.Migrations. It registers packages just as New does, and returns an error if configuration or package registration fails. laraveltest.RefreshDatabase calls this to prepare the test database before constructing the application.

func Once

func Once[T any](fn func(ctx context.Context) (T, error)) func(ctx context.Context) (T, error)

Once wraps fn so it runs at most once per unit of work (each HTTP request, job attempt, command, scheduled task, or test client.Context). Subsequent calls in the same unit of work return the cached value and error, and concurrent calls wait for the first execution to finish so middleware and handlers can share one query:

var UserCount = laravel.Once(func(ctx context.Context) (int64, error) {
	return model.Query[models.User]().Count(ctx)
})

Background work started from a request shares that request's memoized values. Results from panics or canceled contexts are not cached. The returned function panics when ctx does not carry an application scope, or when fn re-enters itself (directly or through a mutual dependency), which would otherwise deadlock.

func OnceFor

func OnceFor[K comparable, T any](fn func(ctx context.Context, key K) (T, error)) func(ctx context.Context, key K) (T, error)

OnceFor wraps fn so it runs at most once per key in each unit of work, memoizing each key independently with the same lifecycle and panic rules as Once:

var FindUser = laravel.OnceFor(func(ctx context.Context, id int64) (*models.User, error) {
	return model.Find[models.User](ctx, id)
})

func Report

func Report(ctx context.Context, err error)

Report records err without aborting the current operation. Use it from code that holds a context rather than a request, such as a job, command, or shared service:

if err := search.Index(ctx, post); err != nil {
	laravel.Report(ctx, fmt.Errorf("indexing post %d: %w", post.ID, err))
}

Report logs err and invokes the Report hook configured in Options.Errors, skipping errors that handlers do not report (such as 404 responses). When called during an HTTP request, it behaves identically to r.Report. Report panics when ctx does not carry an application scope, such as context.Background.

func Run

func Run(options Options)

Run builds an App from options and executes the command named on the command line, as App.Run does. It is the standard entry point for main:

func main() {
	laravel.Run(bootstrap.Options())
}

Run closes the application after the command finishes, flushing any pending trace spans. If building the application or running the command fails, Run prints the error to stderr and exits with status 1 (or status 2 for invalid CLI usage). A command that returns a *console.ExitError exits with its status code, and a command interrupted by a signal exits with status 130.

func ServicesOf

func ServicesOf[T any](ctx context.Context) T

ServicesOf returns the registered services value of type T from the application attached to ctx, whether created by Options.Services or registered by a package with Registrar.Services. Wrap it in a helper function for your application or package:

func From(ctx context.Context) *Services {
	return laravel.ServicesOf[*Services](ctx)
}

It panics when ctx does not carry an application scope or when no services of type T are registered.

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is a configured Laravel application. It implements http.Handler to serve HTTP requests, and App.Run executes its CLI commands.

func New

func New(options Options) (*App, error)

New builds an App from options. It returns an error joining every startup problem when the configuration is invalid, a package fails to register, or route definitions conflict.

func (*App) Call

func (a *App) Call(ctx context.Context, c *console.Console, args ...string) error

Call runs a command with explicit arguments (such as "migrate", "--force") using c for console I/O and returns the command's error. When args is empty, Call runs serve just as App.Run does. Unlike App.Run, Call does not install signal handlers, so the command stops only when ctx is canceled.

func (*App) Close

func (a *App) Close() error

Close flushes pending trace spans (up to five seconds), waits up to five seconds for buffered Laravel Cloud log lines, and closes the application's database pools, Redis clients, queue connections, and daily log files. It returns any errors joined with errors.Join.

func (*App) Config

func (a *App) Config() *config.Config

Config returns the application's config.Config. Code that already has a scoped context, such as a handler, job, or command, should call config.From instead.

func (*App) Context

func (a *App) Context(ctx context.Context) context.Context

Context returns a copy of ctx carrying the application scope. Use this when you hold an *App outside a framework entry point, such as in a custom main function:

ctx := app.Context(context.Background())
name := config.From(ctx).App.Name

Requests, jobs, listeners, commands, scheduled tasks, ticks, and seeders already receive a scoped context.

func (*App) Routes

func (a *App) Routes() []web.Route

Routes returns the registered HTTP routes in registration order, followed by any fallback routes.

func (*App) Run

func (a *App) Run(ctx context.Context) error

Run parses os.Args and executes the requested command. When no command is given, it runs serve until ctx is canceled or the process receives SIGINT or SIGTERM.

On SIGINT or SIGTERM, Run cancels the command's context so the command can finish in-flight work and return cleanly. A second signal terminates the process immediately.

Run installs the application's logger as the default slog logger and exports .env variables into the process environment, so call it from main before starting other goroutines.

func (*App) Seed

func (a *App) Seed(ctx context.Context, names ...string) error

Seed runs the named seeders in order, or every registered seeder when names is empty, using ctx so writes join any active transaction (such as a test transaction from laraveltest's client.Seed):

err := app.Seed(ctx, "roles", "products")

It returns an error if any name does not match a registered seeder or if a seeder returns an error.

func (*App) Serve

func (a *App) Serve(ctx context.Context, addr string) error

Serve starts an HTTP server on addr (such as ":8080") and runs the application's Tick tasks. Use this in a custom main function when you run the application alongside other services:

app, err := laravel.New(options)
if err != nil {
	log.Fatal(err)
}
defer app.Close()

if err := app.Serve(ctx, ":8080"); err != nil {
	log.Fatal(err)
}

Serve stops accepting connections when ctx is canceled or the process receives SIGINT or SIGTERM, then waits up to SERVER_SHUTDOWN_TIMEOUT for in-flight requests, background work, and shutdown ticks to finish. It returns an error before listening if APP_KEY is set to an invalid value or if binding addr fails. Unlike App.Run, Serve does not set the default logger or export .env variables into the process environment.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches an HTTP request through the application's middleware and router.

func (*App) Ticks

func (a *App) Ticks() []Tick

Ticks returns a copy of the application's registered ticks, with package ticks followed by Options.Ticks.

func (*App) WaitBackground

func (a *App) WaitBackground(ctx context.Context) error

WaitBackground blocks until all background work completes or ctx is canceled, returning ctx.Err() if ctx ends first. The serve command, CLI commands, and laraveltest already wait automatically, so call WaitBackground only from a custom main function that starts background work directly.

type Argument

type Argument struct {
	// Name is the argument's placeholder name in help output, such as ID.
	Name string
	// Description explains what the argument represents.
	Description string
	// Required causes command parsing to fail when the caller omits the
	// argument.
	Required bool
	// Many allows the final argument to accept one or more values, such as a
	// list of IDs.
	Many bool
}

Argument describes a positional argument declared by a Command's Arguments method.

type Command

type Command interface {
	// Name returns the CLI command name, such as posts:prune. A colon groups
	// commands with the same prefix in the list output.
	Name() string
	// Description returns the one-line summary shown in list and at the top of
	// the command's help output.
	Description() string
	// Run executes the command. Its context is canceled when the process
	// receives SIGINT or SIGTERM. Returning an error prints it and exits with
	// status 1, except for [*console.ExitError] (which exits with its code),
	// [*console.UsageError] (which also prints the command's usage and exits
	// with status 2), and context cancellation caused by a signal (which
	// exits with status 130 without printing).
	Run(ctx context.Context, c *console.Console) error
}

Command defines a CLI command invoked by name, like migrate. Register custom commands in Options.Commands:

// PrunePosts deletes stale drafts.
type PrunePosts struct {
	days int
}

func (*PrunePosts) Name() string        { return "posts:prune" }
func (*PrunePosts) Description() string { return "Delete drafts that nobody has edited in a while" }

func (p *PrunePosts) Flags(flags *flag.FlagSet) {
	flags.IntVar(&p.days, "days", 30, "Delete drafts last edited more than this many `days` ago")
}

func (p *PrunePosts) Run(ctx context.Context, c *console.Console) error {
	deleted, err := db.Table("posts").WhereNull("published_at").
		Where("updated_at", "<", time.Now().AddDate(0, 0, -p.days)).Delete(ctx)
	c.Successf("Deleted %d drafts.", deleted)

	return err
}

Commands can opt into additional behavior by implementing optional methods:

  • Flags(flags *flag.FlagSet) declares CLI flags, usually bound to struct fields. Laravel parses them before Run, includes them in help output, and exits with status 2 on invalid flags. Every command reserves -q, -v, -vv, -vvv, -n, and -h, so do not declare flags with those names.
  • Arguments() []Argument describes positional arguments, which Run reads from console.Console.Args. Commands without this method accept no positional arguments.
  • Signals() []os.Signal traps the listed signals and delivers them on console.Console.Signals instead of canceling the command's context. A command that traps SIGINT or SIGTERM controls its own shutdown, even on a second Ctrl+C.
  • LongRunning() bool returning true omits the root trace span so long-lived workers do not create a single span lasting the lifetime of the process.
  • WithTicks() bool returning true (on a LongRunning command) runs the application's Tick tasks while the command executes, with HostCommand as the process host.
  • Aliases() []string lists alternate names for invoking the command, such as publish for posts:publish, which also appear in help output.

When a Command is a pointer to a struct, Laravel runs each invocation on a fresh copy so flag values from one run never leak into the next.

type Host

type Host struct {
	// Kind identifies whether the process is a server, queue worker, or
	// long-running console command.
	Kind HostKind
	// Connection is the queue connection name when Kind is [HostWorker].
	Connection string
	// Queues lists the queue names worked when Kind is [HostWorker].
	Queues []string
	// Command is the command name when Kind is [HostCommand].
	Command string
}

Host describes the long-running process hosting the application, passed to Tick.When and returned by CurrentHost.

func CurrentHost

func CurrentHost(ctx context.Context) (Host, bool)

CurrentHost returns the long-running Host hosting the current process (HTTP server, queue worker, or long-running console command with ticks), and whether ctx is running inside one. One-off commands and tests return the zero Host and false.

func (Host) IsCommand

func (h Host) IsCommand() bool

IsCommand reports whether h is a long-running console command.

func (Host) IsServer

func (h Host) IsServer() bool

IsServer reports whether h is the HTTP server.

func (Host) IsWorker

func (h Host) IsWorker() bool

IsWorker reports whether h is a queue worker.

type HostKind

type HostKind uint8

HostKind identifies which kind of long-running process is hosting the application.

const (
	// HostServer is the HTTP server (serve or [App.Serve]).
	HostServer HostKind = iota + 1
	// HostWorker is a queue worker (queue:work).
	HostWorker
	// HostCommand is a long-running console command that enables ticks by
	// implementing WithTicks() bool.
	HostCommand
)

type Listener

type Listener interface {
	// contains filtered or unexported methods
}

Listener handles dispatched application events registered in Options.Listeners. Create one with Listen, ListenAtDispatch, or ListenQueued:

var All = []laravel.Listener{
	laravel.Listen(SendReceipt),
}

func Listen

func Listen[E any](handle func(ctx context.Context, event E) error) Listener

Listen creates a Listener that calls handle for each dispatched event of type E:

func SendReceipt(ctx context.Context, e events.OrderPlaced) error {
	// Email the receipt...
}

When E is an interface type, handle receives every dispatched event that implements E. If an event is dispatched inside a database transaction, handle waits until the transaction commits, as event.Dispatcher.Dispatch describes.

func ListenAtDispatch

func ListenAtDispatch[E any](handle func(ctx context.Context, event E) error) Listener

ListenAtDispatch creates a Listener that runs immediately during dispatch with the caller's context rather than waiting for a transaction to commit. Inside a database transaction, writes through ctx join that transaction so they commit or roll back together, and returning an error fails the dispatch:

func ReserveStock(ctx context.Context, e events.OrderPlaced) error {
	return model.Create(ctx, &models.Reservation{OrderID: e.OrderID})
}

type Middleware

type Middleware struct {
	// Global runs on every incoming request before routing.
	Global web.Stack
	// Web runs on routes registered in [Routes.Web].
	Web web.Stack
	// API runs on routes registered in [Routes.API].
	API web.Stack
	// Proxies lists IP addresses and CIDR networks whose X-Forwarded-* headers
	// Laravel trusts, such as 10.0.0.0/8. Use "*" to trust every proxy. On
	// Laravel Cloud, Proxies defaults to "*".
	Proxies []string
}

Middleware holds the application's global, web, and API middleware stacks along with trusted proxy rules. Options.Middleware receives Laravel's default stacks so you can append, prepend, replace, or remove entries:

Middleware: func(m *laravel.Middleware, cfg *config.Config) {
	m.Web.Append(web.MiddlewareFunc(shareLocale))
	m.Replace(middleware.ValidateCSRFToken{Except: []string{"webhooks/*"}})
	m.Proxies = []string{"10.0.0.0/8"}
},

func (*Middleware) Remove

func (m *Middleware) Remove(middleware ...web.Middleware)

Remove deletes every middleware matching the type of any argument from Middleware.Global, Middleware.Web, and Middleware.API.

func (*Middleware) Replace

func (m *Middleware) Replace(replacement web.Middleware)

Replace substitutes replacement for every middleware of the same type across Middleware.Global, Middleware.Web, and Middleware.API, preserving its position in each stack.

type Options

type Options struct {
	// Config supplies a prebuilt application configuration. When nil, [New]
	// builds one from [Options.Env] with [config.FromEnv].
	Config *config.Config
	// Configure adjusts Laravel's configuration for settings that do not fit
	// neatly into environment variables, such as extra database connections or
	// custom storage disks. It runs on the configuration built by Laravel (or
	// by laraveltest in tests) before packages register, receiving the same
	// [config.Env] used to read application settings:
	//
	//	Configure: func(cfg *config.Config, env *config.Env) {
	//		cfg.Database.Connections = map[string]config.Connection{
	//			"reporting": {URL: env.String("REPORTING_DATABASE_URL", "")},
	//		}
	//	},
	//
	// Any invalid variable read from env stops [New] from starting the
	// application.
	Configure func(cfg *config.Config, env *config.Env)
	// Env provides the environment variables that Laravel reads when
	// [Options.Config] is nil and that packages and services read for their
	// own settings. When nil, Laravel reads the process environment and the
	// .env file in the application's root directory.
	Env *config.Env
	// Packages lists the [Package] values installed in the application. Each
	// package registers its routes, middleware, assets, migrations, and
	// commands in order before your own options apply, so your application
	// settings take precedence.
	Packages []Package
	// Routes registers the application's HTTP routes and broadcast channels.
	Routes Routes
	// Middleware customizes the application's middleware stacks. It receives
	// Laravel's default [Middleware] after packages have made their changes.
	Middleware func(m *Middleware, cfg *config.Config)
	// Users registers custom [go.laravel.com/auth.Users] implementations for
	// user types that need custom lookups, such as excluding suspended
	// accounts:
	//
	//	Users: []laravel.UserProvider{laravel.Users[models.User](models.Users{})},
	//
	// Laravel uses the registered provider across session logins, request
	// guards, password resets, and email verification. User types without a
	// custom provider use [go.laravel.com/auth.ModelUsers]. Registering two
	// providers for the same user type causes [New] to return an error.
	Users []UserProvider
	// Views supplies the application's html/template files from
	// resources/views (typically embedded as resources.Views). A view's name
	// is its path without the file extension, using dots instead of slashes,
	// such as posts.show. Files under vendor/mail override Laravel's built-in
	// mail components. When [config.App.Debug] is true, Laravel reads views
	// from resources/views on disk so template edits appear without a restart.
	Views fs.FS
	// ViewFuncs returns custom template functions made available to every
	// view. The closure receives a context that carries each render's scope
	// when the returned functions are called; read from ctx inside the
	// returned functions rather than before returning the map, because
	// Laravel also invokes the closure at startup with an empty context to
	// discover function names:
	//
	//	ViewFuncs: func(ctx context.Context) template.FuncMap {
	//		return template.FuncMap{"team": func() *models.Team { return shared.Team(ctx) }}
	//	},
	//
	// A function with the same name as a built-in or package function replaces
	// it.
	ViewFuncs func(ctx context.Context) template.FuncMap
	// Errors customizes how Laravel reports and renders errors.
	Errors web.Errors
	// Password sets the application's default password complexity rules used by
	// [rule.Password], such as rule.Password.Min(8).Letters().MixedCase().Numbers().
	// When left at its zero value, [rule.Password] requires at least 8
	// characters.
	Password rule.PasswordRule
	// Head sets the default HTML head metadata for every page, such as
	// descriptions and social tags.
	Head head.Config
	// Logger receives request logs and reported errors. When nil, Laravel
	// builds a logger from the channels listed in LOG_CHANNEL as [config.Log]
	// describes.
	//
	// The request log emits one info entry per request with its status code
	// and duration. If a client disconnects before the response completes, the
	// entry records status 499.
	Logger *slog.Logger
	// LogHandler wraps the application's [slog.Handler] so you can forward log
	// records to a custom destination, such as an error tracker, alongside the
	// configured channels or [Options.Logger]. It receives the existing
	// handler and returns the outer handler that sees every record first:
	//
	//	LogHandler: func(next slog.Handler, env *config.Env) (slog.Handler, error) {
	//		return slog.NewMultiHandler(next, web.LogHandler(tracker.Handler(slog.LevelError))), nil
	//	},
	//
	// It runs once before [Options.Services] and wraps any handlers registered
	// by packages. Returning an error stops [New] from starting the
	// application.
	LogHandler func(next slog.Handler, env *config.Env) (slog.Handler, error)
	// Drivers registers the database drivers available to the application,
	// such as postgres.Driver. Laravel selects the driver from the scheme of
	// DATABASE_URL and each named connection URL.
	Drivers []db.Driver
	// QueryListener runs after every successful database query across all
	// connections, for example to log slow queries.
	QueryListener db.Listener
	// Cache overrides the application's default cache store with a custom
	// [cache.Store]. When nil, Laravel uses the store named by CACHE_STORE.
	Cache cache.Store
	// CacheStores registers additional named cache stores, such as a Memcached
	// store. CACHE_STORE, CACHE_FAILOVER_STORES, and [cache.Named] can select
	// them, and a store using a built-in name such as redis replaces the
	// built-in store.
	CacheStores map[string]cache.Store
	// SessionStores registers additional named session stores, such as a
	// Memcached store. SESSION_DRIVER can select them, and a store using a
	// built-in driver name such as file replaces the built-in driver.
	SessionStores map[string]session.Store
	// Migrations lists the application's database migrations (typically
	// defined in database/migrations) that the migrate commands run alongside
	// package migrations.
	Migrations []db.Migration
	// Schema holds the application's schema dumps that schema:dump writes,
	// typically embedded from database/schema as schema.Dumps. A dump is
	// named for its connection, such as default-schema.sql, and a .dump
	// file takes the place of a .sql file for the same connection. migrate
	// loads a connection's dump into a database that has run no migrations,
	// before the migrations that are still pending. A connection without a
	// dump in Schema reads its dump from database/schema on disk.
	Schema fs.FS
	// Seeders lists the application's database seeders (typically defined in
	// database/seeders) that db:seed runs in order.
	Seeders []Seeder
	// Commands registers custom CLI [Command] implementations invoked by name,
	// like migrate. A command with the same name as a package command replaces
	// it.
	Commands []Command
	// DB overrides the application's default database handle, which
	// [App.Close] closes. When nil, [New] opens the database configured by
	// DATABASE_URL. laraveltest.RefreshDatabase sets this to the test's
	// transaction.
	DB *db.DB
	// Morphs registers a zero value of each model type that a polymorphic
	// relationship's type column may reference, such as models.Post{}, so
	// morph_to queries can resolve a model type from its morph name.
	Morphs []any
	// Searchable registers a zero value of each model type that
	// [go.laravel.com/search.Query] searches, such as models.Post{}. Laravel
	// reads each model's search struct tags and keeps its index in sync after
	// model writes. A listed type without search tags, or with a tag Laravel
	// doesn't know, causes [New] to return an error that names the field.
	Searchable []any
	// SearchEngines registers custom search engines by name. SEARCH_ENGINE
	// can select one, and an engine named like one of Laravel's or a
	// package's replaces it.
	SearchEngines map[string]search.Engine
	// SearchEmbedder embeds the text of searchable models with an embedding
	// field when they sync, and the terms of semantic and hybrid searches.
	// Set it to a [go.laravel.com/search.Embedder] that calls your embedding
	// provider.
	SearchEmbedder search.Embedder

	// Listeners registers the application's event listeners (typically defined
	// in listeners.All). They run after any listeners registered by packages.
	Listeners []Listener
	// Features registers the application's feature flag definitions so
	// [feature.Active] can evaluate them and feature:purge --except-defined
	// preserves them.
	Features []feature.Definition
	// FeatureStore overrides the storage backend for feature flags with a
	// custom [feature.Store]. When nil, Laravel uses the store named by
	// FEATURE_STORE.
	FeatureStore feature.Store
	// Mailers registers custom mail transports by name. MAIL_MAILER can select
	// them, and a mailer using a built-in name such as ses replaces the
	// built-in mailer.
	Mailers map[string]mail.Transport
	// SlackActions registers a zero value of each [slack.Action] type handled
	// by your Slack buttons and menus, such as actions.Refund{}, so
	// [slack.Interactions] and queue workers can resolve an action by name.
	// Packages register theirs through [Registrar.SlackActions].
	SlackActions []slack.Action
	// Jobs registers a zero value of each queued job and callback type the
	// application dispatches (typically defined in jobs.All), such as
	// jobs.ProcessPodcast{}, so queue workers can resolve a job by name.
	Jobs []any
	// Workflows registers a zero value of each workflow type the application
	// starts, such as workflows.OnboardUser{}, so workers can resolve a
	// workflow run by name.
	Workflows []any
	// WorkflowStore overrides the storage backend for durable workflows with a
	// custom [workflow.Store]. When nil, Laravel uses the store named by
	// WORKFLOW_STORE.
	WorkflowStore workflow.Store
	// Register registers application components that depend on the resolved
	// [config.Env] or [config.Config], such as custom mailers, OAuth providers,
	// queue connections, or stores. It runs after all [Options.Packages] so the
	// application can override package and built-in registrations, and receives
	// the test environment in tests:
	//
	//	Register: func(app *laravel.Registrar) error {
	//		app.Mailer("marketing", &resend.Transport{
	//			Key: app.Env().String("RESEND_MARKETING_KEY", ""),
	//		})
	//
	//		return nil
	//	},
	Register func(app *Registrar) error
	// Services constructs the application's own services, such as third-party
	// API clients. [New] calls it once after building the framework's own
	// services and starting tracing. A service may hold a client created with
	// package httpclient, which dispatches requests through the application in
	// each call's context so test fakes intercept them. Pass your constructor
	// through [BuildServices] and expose it with [ServicesOf] (for example,
	// services.From(r) in handlers or services.From(ctx) in jobs and
	// commands). Tests build the same services from the test environment and
	// can swap individual fields directly.
	Services func(env *config.Env, app *App) any
	// QueueConnections adds custom queue connections or replaces entries in
	// [config.Queue.Connections] by name.
	QueueConnections map[string]queue.Connection

	// NotificationChannels registers custom notification channels, such as
	// Discord, alongside channels registered by packages. Build one with
	// [notification.NewChannel].
	NotificationChannels []notification.Channel

	// SocialProviders adds [social.OAuth2] login providers under the names
	// that [social.Redirect] and [social.User] accept, such as gitlab:
	//
	//	SocialProviders: map[social.Provider]social.OAuth2{
	//		"gitlab": {
	//			AuthorizeURL: "https://gitlab.com/oauth/authorize",
	//			TokenURL:     "https://gitlab.com/oauth/token",
	//			Scopes:       []string{"openid", "profile", "email"},
	//			ClientID:     env.String("GITLAB_CLIENT_ID", ""),
	//			ClientSecret: env.String("GITLAB_CLIENT_SECRET", ""),
	//			User:         social.UserInfo("https://gitlab.com/oauth/userinfo"),
	//		},
	//	},
	//
	// A provider with the name of a package's replaces the package's, and one
	// named google, github, or microsoft replaces Laravel's. A provider
	// without a User function causes [New] to return an error.
	SocialProviders map[social.Provider]social.OAuth2

	// HTTP customizes the application's HTTP client used by package
	// httpclient. It receives Laravel's default client and returns the client
	// to use, for example with a custom timeout or hooks. Build on the client
	// passed in so test fakes continue to intercept requests.
	HTTP func(client *httpclient.Client) *httpclient.Client
	// Lottery overrides random lottery draws, such as with lottery.AlwaysWin
	// in tests. laraveltest.Lottery sets this field.
	Lottery lottery.Results

	// Ticks registers periodic [Tick] tasks that run inside each server
	// process, queue worker, and long-running command with WithTicks()
	// alongside package ticks.
	Ticks []Tick
	// Schedule registers the application's scheduled tasks (typically defined
	// in commands.Schedule) after package schedules. The context carries the
	// application scope so tasks can read settings with [config.From].
	Schedule func(ctx context.Context, s *schedule.Schedule)

	// TracerProvider exports traces instead of the default OTLP exporter
	// configured by OTEL_* variables. If the provider implements a Shutdown
	// method, [App.Close] calls it when shutting down.
	TracerProvider trace.TracerProvider
}

Options configures a Laravel application passed to New or Run. Every field is optional.

type Package

type Package interface {
	// Register registers the package's components on app. The application's
	// [config.Config] is final by the time Register runs, so you can read it
	// from [Registrar.Config] and read package-specific variables from
	// [Registrar.Env]. Returning an error prevents [New] from starting the
	// application.
	//
	// Laravel may call Register more than once on the same Package value (for
	// example, when [Migrations] collects migrations before [New] builds the
	// application), so Register must produce the same registrations each time.
	Register(app *Registrar) error
}

Package extends a Laravel application with routes, middleware, assets, views, migrations, commands, and other components. Install packages by listing them in Options.Packages:

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

type QueuedListener

type QueuedListener[E, J any] struct {
	// contains filtered or unexported fields
}

QueuedListener is a Listener created by ListenQueued that dispatches a queued job for each matching event.

func ListenQueued

func ListenQueued[E, J any](job func(event E) J) QueuedListener[E, J]

ListenQueued creates a QueuedListener that turns each dispatched event of type E into a job of type J and pushes it onto the application's queue. The returned job is a standard queue job with a Handle method and optional JobOptions, Failed, Middleware, DebounceID, and JobName methods:

type SendReceipt struct {
	OrderID int64
	Email   string
}

func QueueReceipt(e events.OrderPlaced) SendReceipt {
	return SendReceipt{OrderID: e.OrderID, Email: e.Email}
}

func (j SendReceipt) Handle(ctx context.Context) error {
	// Email the receipt...
}

var All = []laravel.Listener{
	laravel.ListenQueued(QueueReceipt),
}

Laravel automatically registers job type J with the queue. If J implements ShouldQueue() bool and returns false, the listener skips pushing the job. When an event is dispatched inside a transaction, the job is pushed only after the transaction commits and is discarded on rollback. Any push error (or execution error on the sync connection) is returned as the listener's error.

func (QueuedListener[E, J]) Connection

func (l QueuedListener[E, J]) Connection(name string) QueuedListener[E, J]

Connection returns a copy of l that dispatches its jobs to the named queue connection instead of the default connection.

func (QueuedListener[E, J]) Delay

func (l QueuedListener[E, J]) Delay(d time.Duration) QueuedListener[E, J]

Delay returns a copy of l that waits d before making dispatched jobs available to workers.

type Registrar

type Registrar struct {
	// contains filtered or unexported fields
}

Registrar collects the routes, middleware, views, migrations, commands, and services that a Package registers during Package.Register. Each method corresponds to a field on Options, and the application's own options apply after all packages so the application always takes precedence.

func (*Registrar) API

func (r *Registrar) API(routes func(route *routing.Router, cfg *config.Config))

API registers stateless routes under Routes.APIPrefix alongside Routes.API, running with the API middleware stack.

func (*Registrar) Assets

func (r *Registrar) Assets(namespace string, files fs.FS)

Assets mounts static files from files (such as stylesheets and scripts) at /vendor/<namespace>/. Views reference them with view.VendorAsset (for example, view.VendorAsset(ctx, "inspire", "inspire.css")), and an application can override any file by placing its own copy in public/vendor/<namespace>/.

func (*Registrar) Bare

func (r *Registrar) Bare(routes func(route *routing.Router, cfg *config.Config))

Bare registers routes with no URL prefix and without the web or API middleware stacks alongside Routes.Bare, such as webhooks that do not use sessions or CSRF tokens.

func (*Registrar) CacheStore

func (r *Registrar) CacheStore(name string, store cache.Store)

CacheStore registers a named cache.Store that CACHE_STORE or CACHE_FAILOVER_STORES can select. Built-in store names (memory, database, redis, failover, and discard) are reserved and cause New to return an error.

func (*Registrar) Channels

func (r *Registrar) Channels(channels func(channel *routing.Channels))

Channels registers authorization callbacks for the package's private and presence broadcast channels alongside Routes.Channels. Package patterns match before the application's, so prefix them with your package name, such as billing.invoices.{invoice}. Leave routing.Channels.Via to the application, since it selects the broadcast connection for all channels.

func (*Registrar) Commands

func (r *Registrar) Commands(commands ...Command)

Commands registers CLI Command implementations alongside Options.Commands. An application command with the same name replaces the package's command.

func (*Registrar) Config

func (r *Registrar) Config() *config.Config

Config returns the application's final config.Config.

func (*Registrar) Env

func (r *Registrar) Env() *config.Env

Env returns the config.Env that the package reads its own settings from, combining the process environment and .env file (or Options.Env when set). Any invalid variable read from Env causes New to return an error.

func (*Registrar) Errors

func (r *Registrar) Errors(errs web.Errors)

Errors customizes error reporting and rendering alongside Options.Errors, for example to keep sensitive fields out of old input or render a custom error response:

app.Errors(web.Errors{
	Ignore:    func(err error) bool { return errors.Is(err, ErrCardDeclined) },
	DontFlash: []string{"card.number", "card.cvc"},
})

The application's own Options.Errors takes precedence over packages: its Render runs first and falls back to packages when it returns nil, while its Respond runs last on the response returned by packages. Every Report hook runs, any matching Ignore suppresses reporting, and every DontFlash field is excluded from old input.

func (*Registrar) FeatureStore

func (r *Registrar) FeatureStore(name string, store feature.Store)

FeatureStore registers a named feature.Store that FEATURE_STORE can select. Built-in store names (database and memory) are reserved and cause New to return an error.

func (*Registrar) Features

func (r *Registrar) Features(flags ...feature.Definition)

Features registers the package's feature flag definitions alongside Options.Features so feature:purge --except-defined preserves them.

func (*Registrar) Jobs

func (r *Registrar) Jobs(jobs ...any)

Jobs registers the package's queued job and callback types alongside Options.Jobs.

func (*Registrar) Listeners

func (r *Registrar) Listeners(listeners ...Listener)

Listeners registers event Listener values that run before the application's own listeners in Options.Listeners for the same events.

func (*Registrar) LogHandler

func (r *Registrar) LogHandler(wrap func(next slog.Handler) slog.Handler)

LogHandler wraps the application's slog.Handler so the package can inspect or forward log records, such as sending errors to an external tracker. The wrap function receives the current handler and returns the outer handler that delegates to next:

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

Handlers receive the context passed to each log call, so web.RequestID returns the active request ID. Packages registered later wrap earlier ones, and Options.LogHandler wraps all packages.

func (*Registrar) Mailer

func (r *Registrar) Mailer(name string, transport mail.Transport)

Mailer registers a named mail.Transport that MAIL_MAILER can select. A mailer with the same name in Options.Mailers replaces the package's mailer. Passing an empty name, a nil transport, or a name already taken by another package causes New to return an error.

func (*Registrar) Middleware

func (r *Registrar) Middleware(change func(m *Middleware))

Middleware customizes the application's Middleware stacks before Options.Middleware runs, allowing the application to adjust or remove middleware a package adds.

func (*Registrar) Migrations

func (r *Registrar) Migrations(migrations ...db.Migration)

Migrations registers database migrations that the migrate commands run alongside Options.Migrations in name order.

func (*Registrar) NotificationChannels

func (r *Registrar) NotificationChannels(channels ...notification.Channel)

NotificationChannels registers custom notification channels, such as Discord, alongside Options.NotificationChannels. Build channels with notification.NewChannel.

func (*Registrar) QueueConnection

func (r *Registrar) QueueConnection(name string, connection queue.Connection)

QueueConnection registers a named queue.Connection backed by the package's queue driver. A connection with the same name in Options.QueueConnections replaces the package's connection. Passing an empty name, a connection without a driver, or a name already taken by another package causes New to return an error.

func (*Registrar) Schedule

func (r *Registrar) Schedule(define func(ctx context.Context, s *schedule.Schedule))

Schedule registers scheduled tasks that run before Options.Schedule:

app.Schedule(func(ctx context.Context, s *schedule.Schedule) {
	s.Command("reports:generate").DailyAt("06:00")
})

func (*Registrar) SearchEngine

func (r *Registrar) SearchEngine(name string, engine search.Engine)

SearchEngine registers a named search.Engine that SEARCH_ENGINE can select. An engine with the same name in Options.SearchEngines replaces the package's engine. Passing an empty name, a nil engine, or a name already taken by another package causes New to return an error.

func (*Registrar) Seeders

func (r *Registrar) Seeders(seeders ...Seeder)

Seeders registers database seeders that db:seed runs in order before Options.Seeders. An application seeder with the same name replaces the package's seeder.

func (*Registrar) Services

func (r *Registrar) Services(services any)

Services registers the package's services value so the package's jobs, handlers, and application code can retrieve it with ServicesOf. Register a single value of a package-owned type:

func (q *Quotes) Register(app *laravel.Registrar) error {
	app.Services(q)
	app.Jobs(SendDailyQuote{})

	return nil
}

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

Passing nil or registering two services of the same type causes New to return an error.

func (*Registrar) SessionStore

func (r *Registrar) SessionStore(name string, store session.Store)

SessionStore registers a named session.Store that SESSION_DRIVER can select. Built-in driver names (cookie, database, file, memory, and redis) are reserved and cause New to return an error.

func (*Registrar) SlackActions

func (r *Registrar) SlackActions(actions ...slack.Action)

SlackActions registers a zero value of each slack.Action type handled by the package's Slack buttons and menus alongside Options.SlackActions. Prefix each ActionName with your package name (such as billing.refund), because duplicate action names cause New to return an error.

func (*Registrar) SocialProvider

func (r *Registrar) SocialProvider(name social.Provider, provider social.OAuth2)

SocialProvider adds an social.OAuth2 login provider under name, such as gitlab, that social.Redirect and social.User accept. A provider with the same name in Options.SocialProviders replaces the package's provider. Passing a provider without a User function, an empty name, the name of one of Laravel's providers (google, github, or microsoft), or a name already taken by another package causes New to return an error.

func (*Registrar) Ticks

func (r *Registrar) Ticks(ticks ...Tick)

Ticks registers periodic Tick tasks that run inside each server process alongside Options.Ticks. Prefix each tick name with your package name (such as flags:refresh), because duplicate tick names cause New to return an error.

func (*Registrar) ViewFuncs

func (r *Registrar) ViewFuncs(funcs func(ctx context.Context) template.FuncMap)

ViewFuncs registers template functions available in every view alongside Options.ViewFuncs. The closure receives a context that carries each render's scope when the returned functions are called; read from ctx inside the returned functions rather than before returning the map, because Laravel also invokes the closure at startup with an empty context to discover function names. Functions with the same name as built-in functions replace them, and functions in Options.ViewFuncs override package functions.

func (*Registrar) Views

func (r *Registrar) Views(namespace string, files fs.FS)

Views registers html/template files from files (such as an embed.FS) under namespace. Templates render with the namespace prefix, such as web.View("inspire::quote", data), and an application can override any view in resources/views/vendor/<namespace>/. Using a reserved Laravel namespace causes New to return an error.

func (*Registrar) Web

func (r *Registrar) Web(routes func(route *routing.Router, cfg *config.Config))

Web registers browser routes alongside Routes.Web, running with the web middleware stack.

func (*Registrar) WorkflowStore

func (r *Registrar) WorkflowStore(name string, store workflow.Store)

WorkflowStore registers a named workflow.Store that WORKFLOW_STORE can select. The built-in store names (database and memory) are reserved and cause New to return an error.

func (*Registrar) Workflows

func (r *Registrar) Workflows(workflows ...any)

Workflows registers the package's workflow types alongside Options.Workflows.

type Routes

type Routes struct {
	// Web registers browser routes. They run with the web middleware stack
	// (encrypted cookies, sessions, and CSRF protection) and receive the
	// application's [config.Config] so you can register routes conditionally
	// by environment.
	Web func(route *routing.Router, cfg *config.Config)
	// API registers stateless routes mounted under [Routes.APIPrefix]. They
	// run with the API middleware stack and render errors as JSON, including a
	// JSON 404 for unmatched paths under the prefix.
	API func(route *routing.Router, cfg *config.Config)
	// APIPrefix sets the URL path prefix for [Routes.API], such as /api/v1.
	// When empty, it defaults to /api.
	APIPrefix string
	// Bare registers routes with no URL prefix and without the web or API
	// middleware stacks, such as webhooks that do not use sessions or CSRF
	// tokens.
	Bare func(route *routing.Router, cfg *config.Config)
	// Health sets the health-check endpoint path, such as /up. It responds to
	// GET requests with 200 OK on any host before middleware runs and logs
	// them at debug level. Registering another GET route at the same path
	// causes [New] to return an error. When empty, no health endpoint is
	// registered.
	Health string

	// Channels registers authorization callbacks for private and presence
	// broadcast channels. Browsers authenticate at POST /broadcasting/auth
	// using the web middleware stack.
	Channels func(channel *routing.Channels)
}

Routes registers an application's HTTP routes and broadcast channel authorizers.

type Seeder

type Seeder struct {
	// Name identifies the seeder when passed to db:seed, [App.Seed], or
	// [CallSeeder].
	Name string
	// WithoutEvents suppresses model and application events while this seeder
	// runs, as [event.Muted] does.
	WithoutEvents bool
	// Run inserts the seeder's rows using ctx. Every seeder in a run shares
	// one database transaction so a failure rolls back the entire run, and
	// factories share one faker instance. The context also carries the
	// application scope for services such as hashing and storage.
	Run func(ctx context.Context) error
}

Seeder populates the database with initial or sample data, such as a default user or application roles. Register seeders in Options.Seeders (typically defined in database/seeders) so db:seed can run them:

var All = []laravel.Seeder{
	{Name: "users", Run: users},
}

func users(ctx context.Context) error {
	password, err := hash.Make(ctx, "password")
	if err != nil {
		return err
	}

	return db.Table("users").Insert(ctx, db.Values{"email": "taylor@laravel.com", "password": password})
}

type Tick

type Tick struct {
	// Name identifies the tick in logs. Every tick must have a unique name;
	// packages should prefix names with their package name.
	Name string
	// Every sets the delay between consecutive runs, measured from when the
	// previous run finishes so runs never overlap.
	Every time.Duration
	// Jitter adds or subtracts a random duration up to this amount from
	// [Tick.Every] so servers started together do not tick in lockstep. Jitter
	// must be shorter than Every.
	Jitter time.Duration
	// Immediately runs the first tick as soon as the process starts rather than
	// waiting one interval. The process begins handling work without waiting
	// for the first run to finish.
	Immediately bool
	// RunOnShutdown runs the tick one final time during graceful shutdown,
	// after in-flight work and background tasks finish, so buffered state is
	// not lost.
	RunOnShutdown bool
	// When filters which [Host] processes run this tick. Laravel evaluates When
	// before each scheduled run and before a shutdown run. When nil, the tick
	// runs in every host.
	When func(host Host) bool
	// Run executes the tick's work. Laravel reports returned errors and panics
	// the same way it reports handler failures, then schedules the next run as
	// usual. Its context is canceled if the process's shutdown timeout expires.
	Run func(ctx context.Context) error
}

Tick runs a function at a fixed interval inside each server process, queue worker, and long-running console command that enables ticks, such as flushing buffered metrics or view counts. Register ticks in Options.Ticks:

Ticks: []laravel.Tick{
	{Name: "flush-view-counts", Every: 10 * time.Second, Run: counts.Flush, RunOnShutdown: true},
},

The serve command, App.Serve, queue:work, and long-running commands with a WithTicks() bool method returning true run ticks. Other commands and tests do not; call laraveltest's Client.Tick to exercise a tick in tests. Because every matching process runs every tick, use the scheduler for work that must run once across your fleet or at a specific time of day.

type UserProvider

type UserProvider struct {
	// contains filtered or unexported fields
}

UserProvider pairs a user model type with its auth.Users implementation for Options.Users. Construct one with Users.

func Users

func Users[U any](users auth.Users[U]) UserProvider

Users creates a UserProvider that registers users for user type U in Options.Users:

laravel.Users[models.User](models.Users{})

Directories

Path Synopsis
Package auth handles user authentication, route protection, authorization policies, password resets, and email verification.
Package auth handles user authentication, route protection, authorization policies, password resets, and email verification.
social
Package social authenticates users through Google, GitHub, Microsoft, and the providers an application adds, using OAuth and OpenID Connect.
Package social authenticates users through Google, GitHub, Microsoft, and the providers an application adds, using OAuth and OpenID Connect.
Package broadcast sends application events to browsers over WebSockets so pages update when an order ships or a teammate joins a room.
Package broadcast sends application events to browsers over WebSockets so pages update when an order ships or a teammate joins a room.
Package broadcasttest replaces an application's broadcaster with a Fake that records broadcasts instead of publishing or queueing them.
Package broadcasttest replaces an application's broadcaster with a Fake that records broadcasts instead of publishing or queueing them.
Package cache stores JSON-encoded values with expiration times so repeated requests can read a cached result instead of repeating slow work.
Package cache stores JSON-encoded values with expiration times so repeated requests can read a cached result instead of repeating slow work.
Package config holds an application's configuration.
Package config holds an application's configuration.
Package console provides terminal output, styled markup, interactive prompts, and live progress displays for console commands.
Package console provides terminal output, styled markup, interactive prompts, and live progress displays for console commands.
Package cookie constructs and encrypts HTTP cookies for responses.
Package cookie constructs and encrypts HTTP cookies for responses.
Package crypt encrypts and decrypts values using AES with the application's keys.
Package crypt encrypts and decrypts values using AES with the application's keys.
Package date provides calendar helpers, human-readable relative time formatting, an application-scoped clock, and a calendar Date type without a time of day.
Package date provides calendar helpers, human-readable relative time formatting, an application-scoped clock, and a calendar Date type without a time of day.
db
Package db runs database queries on PostgreSQL, MySQL, MariaDB, and SQLite on top of database/sql.
Package db runs database queries on PostgreSQL, MySQL, MariaDB, and SQLite on top of database/sql.
mysql
Package mysql provides Laravel's MySQL and MariaDB driver, built on go-sql-driver/mysql.
Package mysql provides Laravel's MySQL and MariaDB driver, built on go-sql-driver/mysql.
postgres
Package postgres provides Laravel's PostgreSQL driver, built on pgx.
Package postgres provides Laravel's PostgreSQL driver, built on pgx.
sqlite
Package sqlite provides Laravel's SQLite driver, built on modernc.org/sqlite, a pure Go implementation that needs no C compiler.
Package sqlite provides Laravel's SQLite driver, built on modernc.org/sqlite, a pure Go implementation that needs no C compiler.
Package event dispatches application events to registered listeners.
Package event dispatches application events to registered listeners.
Package eventtest replaces an application's event dispatcher with a Fake that records dispatched events instead of running their listeners.
Package eventtest replaces an application's event dispatcher with a Fake that records dispatched events instead of running their listeners.
Package factory builds models populated with realistic fake data for tests and database seeders.
Package factory builds models populated with realistic fake data for tests and database seeders.
Package feature manages feature flags so you can roll out changes gradually, such as enabling a new API for staff first and then for one percent of customers.
Package feature manages feature flags so you can roll out changes gradually, such as enabling a new API for staff first and then for one percent of customers.
Package hash hashes and verifies passwords with bcrypt.
Package hash hashes and verifies passwords with bcrypt.
Package head manages the tags rendered inside a page's <head> element, including the title, meta description, canonical link, robots directives, Open Graph tags, Twitter cards, and JSON-LD structured data.
Package head manages the tags rendered inside a page's <head> element, including the title, meta description, canonical link, robots directives, Open Graph tags, Twitter cards, and JSON-LD structured data.
jsonld
Package jsonld provides common schema.org types for JSON-LD structured data that search engines use to render rich results, such as product prices and availability.
Package jsonld provides common schema.org types for JSON-LD structured data that search engines use to render rich results, such as product prices and availability.
Package httpclient sends outgoing HTTP requests to external APIs, such as GitHub or a payment provider, and supports faking them in tests.
Package httpclient sends outgoing HTTP requests to external APIs, such as GitHub or a payment provider, and supports faking them in tests.
Package httpclienttest replaces an application's outgoing HTTP transport with a Fake that returns scripted responses and records every request, so tests never hit the network.
Package httpclienttest replaces an application's outgoing HTTP transport with a Fake that returns scripted responses and records every request, so tests never hit the network.
Package inertia implements the server side of the Inertia v3 protocol.
Package inertia implements the server side of the Inertia v3 protocol.
Package inspiring provides a built-in collection of inspiring quotes for console commands and examples.
Package inspiring provides a built-in collection of inspiring quotes for console commands and examples.
internal
authguard
Package authguard carries a request's authentication from package auth, which logs users in, to Request.User in package web, which returns the logged-in user.
Package authguard carries a request's authentication from package auth, which logs users in, to Request.User in package web, which returns the logged-in user.
aws
Package aws signs requests to AWS services and finds the credentials that sign them, as the AWS SDKs do, with the standard library alone.
Package aws signs requests to AWS services and finds the credentials that sign them, as the AWS SDKs do, with the standard library alone.
callsite
Package callsite finds where a failure happened, for the location on an error's log line.
Package callsite finds where a failure happened, for the location on an error's log line.
cause
Package cause builds the error that work returns when its context ends.
Package cause builds the error that work returns when its context ends.
cloud
Package cloud sends Laravel Cloud the application's log lines and events over Cloud's socket, and carries a request's Cloud-Request-ID through its context.
Package cloud sends Laravel Cloud the application's log lines and events over Cloud's socket, and carries a request's Cloud-Request-ID through its context.
datetime
Package datetime parses calendar dates and timestamps for request validation.
Package datetime parses calendar dates and timestamps for request validation.
dbrule
Package dbrule extracts database-comparable scalar values from validation fields for Unique and Exists rules across validation/rule and model.
Package dbrule extracts database-comparable scalar values from validation fields for Unique and Exists rules across validation/rule and model.
dot
Package dot reads and writes nested maps by dot path, such as "user.name".
Package dot reads and writes nested maps by dot path, such as "user.name".
fake
Package fake holds the fakes that a test puts in place of an application's services once the application is built, and finds the test that a test client's context belongs to.
Package fake holds the fakes that a test puts in place of an application's services once the application is built, and finds the test that a test client's context belongs to.
hooks
Package hooks lets the framework's packages reach behavior of other packages that applications don't call.
Package hooks lets the framework's packages reach behavior of other packages that applications don't call.
loghandler
Package loghandler wraps an slog.Handler to attach context attributes (trace and span IDs, request IDs, active work tags, and log.With values) at the top level of every log record, even when WithGroup is active.
Package loghandler wraps an slog.Handler to attach context attributes (trace and span IDs, request IDs, active work tags, and log.With values) at the top level of every log record, even when WithGroup is active.
maintenance
Package maintenance reads and writes the file that puts an application down for maintenance, storage/framework/down, and signs the cookie that lets a visitor with the secret through.
Package maintenance reads and writes the file that puts an application down for maintenance, storage/framework/down, and signs the cookie that lets a visitor with the secret through.
querycheck
Package querycheck carries omitted-default conflict attribution from package validation back to web.Request.QueryInto without exposing query-stripping plumbing in validation's public API.
Package querycheck carries omitted-default conflict attribution from package validation back to web.Request.QueryInto without exposing query-stripping plumbing in validation's public API.
querylog
Package querylog marks the queries that the framework runs over and over to wait for work, such as a queue worker's poll, so the debug log leaves them out and shows the queries that do work.
Package querylog marks the queries that the framework runs over and over to wait for work, such as a queue worker's poll, so the debug log leaves them out and shows the queries that do work.
reason
Package reason holds the reason phrases that error responses show for HTTP statuses.
Package reason holds the reason phrases that error responses show for HTTP statuses.
reload
Package reload reloads pages in the browser during development: when the application restarts with new code, and when a view in resources/views changes, which the application reads again without a restart.
Package reload reloads pages in the browser during development: when the application restarts with new code, and when a view in resources/views changes, which the application reads again without a restart.
reverb
Package reverb is a Reverb server, which speaks the Pusher protocol that Laravel Echo and pusher-js connect with.
Package reverb is a Reverb server, which speaks the Pusher protocol that Laravel Echo and pusher-js connect with.
routepattern
Package routepattern parses the parameters in route paths and domains, so the router that matches them and the URL generator that fills them read one grammar.
Package routepattern parses the parameters in route paths and domains, so the router that matches them and the URL generator that fills them read one grammar.
scalar
Package scalar parses and coerces scalar request values consistently across binding, validation, rules, and database lookups.
Package scalar parses and coerces scalar request values consistently across binding, validation, rules, and database lookups.
schemadump
Package schemadump finds the schema dump of a database connection, for migrate and for laraveltest.RefreshDatabase.
Package schemadump finds the schema dump of a database connection, for migrate and for laraveltest.RefreshDatabase.
scope
Package scope carries the application in a context, from the entry points that start work, such as the kernel for a request and the command runner, to the packages that read it, such as config.
Package scope carries the application in a context, from the entry points that start work, such as the kernel for a request and the command runner, to the packages that read it, such as config.
socialdrivers
Package socialdrivers carries the social login providers that an application adds from package laravel, which builds the application, to package auth/social, which logs users in with them.
Package socialdrivers carries the social login providers that an application adds from package laravel, which builds the application, to package auth/social, which logs users in with them.
symbol
Package symbol reads the function names the Go runtime reports.
Package symbol reads the function names the Go runtime reports.
telemetry
Package telemetry carries the application's tracer in the context, for the framework's spans and package tracing's.
Package telemetry carries the application's tracer in the context, for the framework's spans and package tracing's.
terminal
Package terminal paints console output: the tones and markers of Laravel's messages, help, and tables, colored when the stream is a terminal that shows colors.
Package terminal paints console output: the tones and markers of Laravel's messages, help, and tables, colored when the stream is a terminal that shows colors.
testviews
Package testviews holds the views that the framework's tests render.
Package testviews holds the views that the framework's tests render.
values
Package values keeps what a context carries for its log lines: the attributes of the work it runs for, such as a command or a job, and the values an application adds with package log, logged or hidden.
Package values keeps what a context carries for its log lines: the attributes of the work it runs for, such as a command or a job, and the values an application adds with package log, logged or hidden.
version
Package version holds the framework's release version, for packages that can't import the root package.
Package version holds the framework's release version, for packages that can't import the root package.
viewrequest
Package viewrequest carries the request a view renders for, from package web, which renders views, to package view, whose helpers read it.
Package viewrequest carries the request a view renders for, from package web, which renders views, to package view, whose helpers read it.
views
Package views holds the framework's views, by namespace: mail's layout and components, the auth emails, and the pagination links.
Package views holds the framework's views, by namespace: mail's layout and components, the auth emails, and the pagination links.
viewset
Package viewset parses an application's views, which are html/template files, with the views of the framework and its packages, and renders them by name.
Package viewset parses an application's views, which are html/template files, with the views of the framework and its packages, and renders them by name.
Package laraveltest boots an isolated Laravel application for integration and feature tests.
Package laraveltest boots an isolated Laravel application for integration and feature tests.
Package log attaches contextual key-value pairs to a context.Context so every log entry written with that context includes them.
Package log attaches contextual key-value pairs to a context.Context so every log entry written with that context includes them.
Package lottery runs probabilistic operations according to configured odds, such as sampling 1 in 100 requests for extra logging or pruning expired sessions on a fraction of requests.
Package lottery runs probabilistic operations according to configured odds, such as sampling 1 in 100 requests for extra logging or pruning expired sessions on a fraction of requests.
Package mail renders and sends transactional email through configured transports such as Resend, Amazon SES, failover, or the local LogTransport.
Package mail renders and sends transactional email through configured transports such as Resend, Amazon SES, failover, or the local LogTransport.
resend
Package resend provides a mail.Transport that delivers email through the Resend HTTP API, along with Resend-specific options for hosted Template rendering and Topic subscriptions.
Package resend provides a mail.Transport that delivers email through the Resend HTTP API, along with Resend-specific options for hosted Template rendering and Topic subscriptions.
ses
Package ses provides a mail.Transport that delivers email through the Amazon SES v2 API, signing each request with AWS Signature Version 4.
Package ses provides a mail.Transport that delivers email through the Amazon SES v2 API, signing each request with AWS Signature Version 4.
Package mailtest replaces an application's mail transport with a Fake that records sent and queued emails instead of delivering them to a mail provider.
Package mailtest replaces an application's mail transport with a Fake that records sent and queued emails instead of delivering them to a mail provider.
Package middleware provides the HTTP middleware that Laravel applications run by default, including EncryptCookies, StartSession, ValidateCSRFToken, TrustHosts, HandleCORS, SpoofMethods, TrimStrings, ConvertEmptyStrings, ValidateSignature, CacheHeaders, Throttle, SecurityHeaders, PreventRequestsDuringMaintenance, and RequireFeature.
Package middleware provides the HTTP middleware that Laravel applications run by default, including EncryptCookies, StartSession, ValidateCSRFToken, TrustHosts, HandleCORS, SpoofMethods, TrimStrings, ConvertEmptyStrings, ValidateSignature, CacheHeaders, Throttle, SecurityHeaders, PreventRequestsDuringMaintenance, and RequireFeature.
Package model reads and writes database rows as Go structs.
Package model reads and writes database rows as Go structs.
Package notification sends short updates to users, such as a paid invoice or a team invite, over email and package-registered channels like SMS or Slack.
Package notification sends short updates to users, such as a paid invoice or a team invite, over email and package-registered channels like SMS or Slack.
Package notificationtest replaces an application's notifier with a Fake that records notifications instead of sending them.
Package notificationtest replaces an application's notifier with a Fake that records notifications instead of sending them.
Package number formats numeric values for human-readable display, including thousands separators, currency amounts, file sizes, percentages, abbreviations, and ordinals.
Package number formats numeric values for human-readable display, including thousands separators, currency amounts, file sizes, percentages, abbreviations, and ordinals.
Package numeric provides Decimal, an arbitrary-precision decimal type for prices, balances, and other exact amounts where float64 rounding is unacceptable.
Package numeric provides Decimal, an arbitrary-precision decimal type for prices, balances, and other exact amounts where float64 rounding is unacceptable.
Package pagination splits query results into pages and builds navigation links between them.
Package pagination splits query results into pages and builds navigation links between them.
Package process executes external programs such as git, ffmpeg, or build scripts, and supports faking them in tests.
Package process executes external programs such as git, ffmpeg, or build scripts, and supports faking them in tests.
Package processtest replaces an application's process runner with a Fake that returns scripted process results and records every invocation, so tests never execute real programs.
Package processtest replaces an application's process runner with a Fake that returns scripted process results and records every invocation, so tests never execute real programs.
Package queue runs slow work asynchronously in background worker processes so HTTP requests can respond immediately.
Package queue runs slow work asynchronously in background worker processes so HTTP requests can respond immediately.
redisqueue
Package redisqueue provides a Redis-backed queue.Driver, queue.BulkPusher, and queue.Sizer using github.com/redis/go-redis/v9.
Package redisqueue provides a Redis-backed queue.Driver, queue.BulkPusher, and queue.Sizer using github.com/redis/go-redis/v9.
sqsqueue
Package sqsqueue provides queue.Driver implementations for Amazon SQS (Driver) and Laravel Cloud managed queues (CloudDriver).
Package sqsqueue provides queue.Driver implementations for Amazon SQS (Driver) and Laravel Cloud managed queues (CloudDriver).
Package queuetest replaces an application's queue with a Fake, runs single job attempts with Attempt, and verifies custom queue drivers with TestDriver.
Package queuetest replaces an application's queue with a Fake, runs single job attempts with Attempt, and verifies custom queue drivers with TestDriver.
Package rate caps how often an action can occur within a time window, such as how many messages a user can send per minute or how many times someone can guess a password.
Package rate caps how often an action can occur within a time window, such as how many messages a user can send per minute or how many times someone can guess a password.
Package redis manages an application's Redis connections and provides Redis-backed cache and session stores built on github.com/redis/go-redis/v9.
Package redis manages an application's Redis connections and provides Redis-backed cache and session stores built on github.com/redis/go-redis/v9.
Package routing maps HTTP requests to handlers by method, host, and path.
Package routing maps HTTP requests to handlers by method, host, and path.
Package schedule defines recurring application tasks, such as a nightly report or an hourly cleanup, in Go rather than in separate cron entries.
Package schedule defines recurring application tasks, such as a nightly report or an hourly cleanup, in Go rather than in separate cron entries.
Package schema creates, alters, drops, and inspects database tables using the connection carried by a context.
Package schema creates, alters, drops, and inspects database tables using the connection carried by a context.
Package search searches models by the text of their fields.
Package search searches models by the text of their fields.
meilisearch
Package meilisearch provides the meilisearch search.Engine, which keeps each searchable model's documents in a Meilisearch index.
Package meilisearch provides the meilisearch search.Engine, which keeps each searchable model's documents in a Meilisearch index.
turbopuffer
Package turbopuffer provides the turbopuffer search.Engine, which keeps each searchable model's documents in a Turbopuffer namespace.
Package turbopuffer provides the turbopuffer search.Engine, which keeps each searchable model's documents in a Turbopuffer namespace.
typesense
Package typesense provides the typesense search.Engine, which keeps each searchable model's documents in a Typesense collection.
Package typesense provides the typesense search.Engine, which keeps each searchable model's documents in a Typesense collection.
Package session stores data for a visitor across HTTP requests.
Package session stores data for a visitor across HTTP requests.
Package slack builds Slack Block Kit messages, delivers them through notifications, installs workspaces via OAuth, and handles interactive buttons and menus.
Package slack builds Slack Block Kit messages, delivers them through notifications, installs workspaces via OAuth, and handles interactive buttons and menus.
Package slacktest replaces an application's Slack client with a Fake that records posted messages and action responses instead of calling Slack.
Package slacktest replaces an application's Slack client with a Fake that records posted messages and action responses instead of calling Slack.
Package sms sends text messages through Telnyx or writes them to the application log during local development.
Package sms sends text messages through Telnyx or writes them to the application log during local development.
Package smstest replaces an application's SMS sender with a Fake that records sent and queued text messages instead of delivering them to a provider.
Package smstest replaces an application's SMS sender with a Fake that records sent and queued text messages instead of delivering them to a provider.
Package storage provides a unified API for reading, writing, and serving files on local directories, S3-compatible object storage, and read-through disks.
Package storage provides a unified API for reading, writing, and serving files on local directories, S3-compatible object storage, and read-through disks.
Package str transforms, inspects, and generates strings for display, identifiers, and formatting.
Package str transforms, inspects, and generates strings for display, identifiers, and formatting.
Package task runs functions concurrently, with a time limit, or in separate goroutines while keeping the application's scope in each piece of work:
Package task runs functions concurrently, with a time limit, or in separate goroutines while keeping the application's scope in each piece of work:
Package tracing creates custom OpenTelemetry spans within your application's traces.
Package tracing creates custom OpenTelemetry spans within your application's traces.
Package urls generates URLs for application paths and named routes, and signs URLs so your application can detect tampering and expiration.
Package urls generates URLs for application paths and named routes, and signs URLs so your application can detect tampering and expiration.
Package validation validates incoming request data against declarative rules before a handler uses it.
Package validation validates incoming request data against declarative rules before a handler uses it.
rule
Package rule provides the built-in validation rules used in a form's Rules method with validation.For and Field:
Package rule provides the built-in validation rules used in a form's Rules method with validation.For and Field:
Package view renders HTML templates from resources/views and provides the built-in template functions available to every view.
Package view renders HTML templates from resources/views and provides the built-in template functions available to every view.
Package vite renders the <script> and <link> tags that load assets from a Vite build or from Vite's development server while it is running:
Package vite renders the <script> and <link> tags that load assets from a Vite build or from Vite's development server while it is running:
Package web provides the core HTTP types shared across Laravel: Request, Response, Handler, Middleware, Kernel, and Error.
Package web provides the core HTTP types shared across Laravel: Request, Response, Handler, Middleware, Kernel, and Error.
Package webtest tests HTTP handlers and Laravel applications in memory, without opening a network socket.
Package webtest tests HTTP handlers and Laravel applications in memory, without opening a network socket.
Package workflow runs durable, multi-step processes that span hours or days and survive sleeps, webhooks, deploys, and worker restarts.
Package workflow runs durable, multi-step processes that span hours or days and survive sleeps, webhooks, deploys, and worker restarts.
Package workflowtest tests durable workflows by faking starts with Fake, driving runs step by step with Start and Run, and verifying custom workflow stores with StoreContract.
Package workflowtest tests durable workflows by faking starts with Fake, driving runs step by step with Start and Run, and verifying custom workflow stores with StoreContract.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL