# Package Development
- [Introduction](#introduction)
- [Creating a package](#creating-a-package)
- [Service providers](#service-providers)
- [What a provider can add](#what-a-provider-can-add)
- [Installing a package](#installing-a-package)
- [Adding the crate](#adding-the-crate)
- [Enabling package features](#enabling-package-features)
- [Registering the provider](#registering-the-provider)
- [Configuration](#configuration)
- [Services](#services)
- [Routes](#routes)
- [Middleware](#middleware)
- [Views](#views)
- [Assets](#assets)
- [Building assets with Vite](#building-assets-with-vite)
- [Migrations](#migrations)
- [Commands and scheduled tasks](#commands)
- [Errors](#errors)
- [Logging](#logging)
- [Checks at boot](#checks-at-boot)
- [Testing packages](#testing-packages)
## Introduction
Packages are the primary way to extend Laravel with reusable functionality, from a payment provider client to a full admin panel with its own routes, views, and database tables.
General-purpose Rust crates such as `reqwest` and `chrono` work in any application by adding them to `Cargo.toml`. Laravel packages go further: they are standard Rust library crates that depend on `laravel-rust` and integrate with an application through a [service provider](#service-providers), adding configuration, services, routes, views, assets, and migrations.
To illustrate each piece, we'll build `example-package`, a package that serves inspiring quotes with its own configuration, service, routes, middleware, views, and stylesheet.
## Creating a package
Create a library crate with `cargo new --lib`, then add `laravel-rust` with default features disabled:
```shell
cargo add laravel-rust --no-default-features
```
Because Cargo unifies enabled features across the dependency graph, keeping default features enabled in a package would force Inertia and MiniJinja onto every application that installs it. Enable `inertia` only if your package uses `laravel::inertia`, `minijinja` only if it calls the MiniJinja engine directly, and `database` if it ships [migrations](#migrations):
```toml
# Cargo.toml
[dependencies]
laravel-rust = { version = "0.1", default-features = false, features = ["database"] }
```
## Service providers
A service provider is a struct implementing `ServiceProvider` that serves as the entry point for everything your package registers:
```rust
use laravel::config::{Config, Env};
use laravel::container::{Container, Registrar};
use laravel::foundation::ServiceProvider;
pub struct InspireServiceProvider;
impl ServiceProvider for InspireServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
// Register your package's default configuration...
}
fn register(&self, app: &mut Registrar) {
// Register services, routes, views, commands, and more...
}
async fn boot(&self, app: &Container) -> laravel::Result<()> {
// Validate configuration or run startup checks...
Ok(())
}
}
```
All three methods are optional. Laravel invokes them in order:
1. **`config`** runs on every provider to register default [configuration](#configuration). Application configuration runs afterward so application settings override package defaults.
2. **`register`** runs on every provider to bind services, routes, views, commands, and other hooks. Configuration is final at this stage, so you can inspect `app.config()` to decide what to register.
3. **`boot`** runs once during application startup, before serving requests or running commands. Use it to resolve services and perform [startup checks](#checks-at-boot).
`register` cannot resolve services directly because services are constructed lazily on first use. When one service depends on another, resolve the dependency inside the service's factory.
### What a provider can add
Inside `register`, `Registrar` exposes builders corresponding to the callbacks in an application's `src/app.rs`:
| Builder | Registers | Counterpart in `src/app.rs` |
| --- | --- | --- |
| `routing()` | [Routes](#routes) and embedded [assets](#assets) | `with_routing` |
| `middleware()` | Global, `web`, and `api` [middleware](#middleware) | `with_middleware` |
| `views()` | [View](#views) namespaces, engines, and shared data | `with_views` |
| `events()` | [Event listeners](events.md) | `with_events` |
| `commands()` | [Console commands](#commands) | `with_commands` |
| `schedule()` | [Scheduled tasks](#commands) | `with_schedule` |
| `ticks()` | [Ticks](tasks.md#ticks) that repeat in the server and queue workers | `with_ticks` |
| `errors()` | Custom [error](#errors) statuses and renderers | `with_errors` |
| `logging()` | Custom [`tracing` layers](#logging) | `with_logging` |
| `head()` | Default [`
` tags](head.md) | `with_head` |
| `migrations()` | Package [migrations](#migrations) | `with_migrations` |
| `sessions()`, `cache()`, `mail()`, `queue()`, `features()` | Custom drivers such as a [session store](session.md#session-stores-of-your-own) or [cache store](cache.md#custom-drivers) | `with_services` |
Packages cannot register [authentication guards](authentication.md#registering-a-guard); only the application registers guards via `with_auth`.
## Installing a package
Installing a Laravel package into an application takes two explicit steps: adding the crate to your `Cargo.toml` and registering its service provider in `src/app.rs`. Registering providers explicitly keeps your application's startup sequence transparent and lets you see every package your application loads in one place.
### Adding the crate
From your application's root directory, add the package using `cargo add`:
```shell
cargo add example-package
```
Cargo resolves the latest compatible version and adds the crate under `[dependencies]` in your `Cargo.toml`:
```toml
[dependencies]
example-package = "0.1.0"
```
When developing a package locally alongside an application, you can point Cargo directly at your local checkout instead using `cargo add --path ../example-package`.
### Enabling package features
To keep compile times fast and binaries small, packages often place optional capabilities (such as a `pdf` feature for exporting quotes as PDFs) behind Cargo features so applications only compile what they actually use. You can enable optional features when adding the package:
```shell
cargo add example-package --features pdf
```
Or enable them directly in `Cargo.toml`:
```toml
[dependencies]
example-package = { version = "0.1.0", features = ["pdf"] }
```
You do not need to manually enable any `laravel-rust` features that a package depends on; Cargo merges the package's required features with your application's automatically during compilation.
### Registering the provider
Adding a crate to `Cargo.toml` makes its types available to import, but it does not wire anything into your application yet. To activate the package's configuration defaults, services, routes, views, middleware, and migrations, register its service provider in `src/app.rs` using `with_providers`:
```rust
use laravel::Application;
Application::configure()
.with_providers(|providers| {
providers.add(example_package::InspireServiceProvider);
})
```
Providers execute in the order they are added, so if two providers bind the same service or setting, the later provider overrides the earlier one. Regardless of where `with_providers` appears in your `Application::configure()` chain, your application's own callbacks (`with_config`, `with_services`, `with_routing`, `with_middleware`, and so on) always run after all providers, ensuring your application can always customize or replace any package default.
## Configuration
Most packages need to expose configurable settings such as API keys, feature toggles, or default behaviors. Inside your package, define a public [configuration section](configuration.md#your-own-config-sections) struct by deriving `Section`, and annotate its fields with `#[env(..)]` attributes so applications can configure them through environment variables:
```rust
use laravel::config::Section;
#[derive(Debug, Clone, Section)]
pub struct InspireConfig {
#[env("INSPIRE_HEADER", default = true)]
pub header: bool,
#[env("INSPIRE_QUOTES", separator = "|")]
pub quotes: Vec,
}
```
While Laravel discovers `#[derive(Section)]` structs in an application's own `app` crate automatically, packages opt in from their service provider's `config` method. Calling `config.discover(env!("CARGO_CRATE_NAME"), env)` inside your package's `ServiceProvider::config` method loads every derived section in your package crate from the environment:
```rust
use laravel::config::{Config, Env};
use laravel::foundation::ServiceProvider;
impl ServiceProvider for InspireServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
}
```
If you need to construct a configuration section in Rust rather than deriving `Section`, you may register it directly with `config.set(..)` inside your package provider's `config` method instead.
Because every package provider's `config` method runs before the application's own `with_config` callback, an application that installs your package can override individual fields in `src/app.rs` while keeping the rest of your package's defaults intact. Derive `Clone` on your section struct so consuming applications can mutate it with `section_mut`:
```rust
// src/app.rs (in the consuming application)
use example_package::InspireConfig;
use laravel::Application;
Application::configure()
.with_config(|config, _| {
config.section_mut::().header = false;
})
```
## Services
Register your package's [services](container.md) inside `register`. For example, this registers a `Quotes` singleton initialized from `InspireConfig`:
```rust
use laravel::container::Registrar;
#[derive(Clone)]
pub struct Quotes {
quotes: Vec,
}
impl Quotes {
pub fn new(quotes: Vec) -> Self {
Self { quotes }
}
pub fn all(&self) -> &[String] {
&self.quotes
}
}
fn register(&self, app: &mut Registrar) {
app.singleton(async |app| {
let config = app.config().section::();
Ok(Quotes::new(config.quotes.clone()))
});
}
```
Because singleton factories run lazily on first resolution, they always see the application's final configuration.
You may also define services using [`#[singleton]` or `#[bind]`](container.md#service-functions) and call `app.discover` to register all attribute-based services, command functions, listeners, and scheduled tasks in your crate at once:
```rust
use laravel::config::Section;
use laravel::container::singleton;
#[singleton]
async fn quotes(config: Section) -> laravel::Result {
Ok(Quotes::new(config.quotes.clone()))
}
fn register(&self, app: &mut Registrar) {
app.discover(env!("CARGO_CRATE_NAME"));
}
```
Applications can inject your service with `Inject` or replace it in `with_services`.
## Routes
Register routes in the `web` or `api` group through `app.routing()`:
```rust
use laravel::container::{Inject, Registrar};
fn register(&self, app: &mut Registrar) {
app.routing().web(|route| {
route.get("/inspire", inspire);
});
}
/// `GET /inspire`: every quote, one per line.
pub async fn inspire(quotes: Inject) -> String {
quotes.all().join("\n")
}
```
Make your route handlers `pub`. Because [routes are identified by their handlers](routing.md#routes-are-identified-by-their-handlers), applications link to package routes via the handler path, such as `route!(example_package::inspire)?`.
## Middleware
Your package can add global, `web`, or `api` [middleware](middleware.md) through `app.middleware()` inside its service provider's `register` method. Because every provider's `config` method and the application's `with_config` callback have already run by the time `register` executes, you can inspect the final `InspireConfig` and attach `AddInspiration` only when `header` is enabled:
```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
impl ServiceProvider for InspireServiceProvider {
fn register(&self, app: &mut Registrar) {
if app.config().section::().header {
app.middleware().web(|web| {
web.append(AddInspiration);
});
}
}
}
```
Consuming applications run their own `with_middleware` callback after all providers, so an application can also remove a package's middleware in `src/app.rs` using `web.remove::()`.
## Views
Because a deployed Laravel application is a single binary without your package's source tree, embed package templates using `laravel::embed!` (resolved relative to your package's `Cargo.toml`) and register them under a namespace:
```rust
use laravel::container::Registrar;
fn register(&self, app: &mut Registrar) {
app.views().namespace("inspire", laravel::embed!("resources/views"));
}
```
Render namespaced views with `view("inspire::quote", data! { quote })`. Applications can override any package view by placing a file at `resources/views/vendor/inspire/quote.html`.
Your package does not need to enable the `minijinja` feature for `.html` views in production, since the application provides the engine. Enable it in dev-dependencies for your package's own tests:
```shell
cargo add --dev laravel-rust --no-default-features --features minijinja
```
In debug builds, Laravel reads embedded files directly from your package directory so template edits appear without recompiling (adding a new file still requires a rebuild).
## Assets
Embed stylesheets, scripts, and images with `laravel::embed!` and register them via `app.routing().assets(..)`. Laravel serves them under `/vendor//`:
```rust
use laravel::container::Registrar;
fn register(&self, app: &mut Registrar) {
app.routing().assets("inspire", laravel::embed!("public"));
}
```
Reference package assets using [`vendor_asset`](urls.md#package-assets) in Rust or templates:
```html
```
Laravel appends a content hash query string (`/vendor/inspire/inspire.css?id=34b6aba9…`) for cache busting. Applications can 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, build the assets before publishing, include the built directory in your published crate, and embed it with `laravel::embed!` so consuming applications do not need Node or Vite.
For a single entry point, this Vite 8 configuration outputs deterministic filenames (`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//` so relative font and image URLs resolve properly. Register the build directory and link the assets from your views:
```rust
fn register(&self, app: &mut Registrar) {
app.routing().assets("dashboard", laravel::embed!("dist"));
}
```
```html
```
#### Including the build in the published crate
Because `embed!` reads built files when an application compiles your package, explicitly include `dist/**` in `Cargo.toml` even if `.gitignore` ignores it:
```toml
[package]
include = ["src/**", "resources/views/**", "dist/**", "Cargo.toml", "README.md", "LICENSE"]
```
Before running `cargo publish`, build your frontend bundle with `npx vite build` and run `cargo package --list` to print every file Cargo will include in the published `.crate` archive. Confirm that `dist/app.js`, `dist/style.css`, and your views appear in the output (and that `node_modules/` does not):
```shell
npx vite build
cargo package --list
```
## Migrations
Packages that store database tables can ship [migrations](migrations.md) and register them via `app.migrations()`. Running `migrate` in an application executes package and application migrations together in filename order:
```rust
use laravel::container::Registrar;
fn register(&self, app: &mut Registrar) {
app.migrations().add(laravel::db::migrations!("database/migrations"));
}
```
Because `laravel::db::migrations!` scans your `database/migrations` directory at compile time, Cargo will not automatically detect newly added migration files unless you instruct it to watch the directory. Add a `build.rs` file at the root of your package crate so Cargo recompiles whenever a migration file is added, edited, or renamed:
```rust
// build.rs
fn main() {
println!("cargo::rerun-if-changed=database/migrations");
}
```
## Commands and scheduled tasks
Packages can register their own [console commands](console.md#writing-commands) so applications gain new CLI commands as soon as the package's service provider is installed. Define a command function in your package with `#[command]`, injecting any services it needs with `Inject`:
```rust
use laravel::console::{Console, command};
use laravel::container::Inject;
/// List every inspiring quote.
#[command("inspire:list")]
pub async fn list_quotes(console: &mut Console, quotes: Inject) {
for quote in quotes.all() {
console.line(quote);
}
}
```
To register your package's `#[command]` functions, call `app.discover(env!("CARGO_CRATE_NAME"))` inside your service provider's `register` method (or register [command structs](console.md#command-structs) explicitly with `app.commands().add::()`). If a consuming application defines a command with the same name, the application's command overrides the package's.
If your package needs to run recurring background work, you can also register [scheduled tasks](scheduling.md) inside your service provider's `register` method via `app.schedule()`:
```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
impl ServiceProvider for BillingServiceProvider {
fn register(&self, app: &mut Registrar) {
app.schedule()
.command("billing:sync-invoices")
.daily_at("08:00");
}
}
```
Scheduled package tasks run automatically whenever the consuming application runs its scheduler.
## Errors
Attach HTTP status codes to your package's domain errors using [`#[derive(Status)]`](errors.md#errors-with-their-own-status) so consuming applications do not have to map each error manually:
```rust
use laravel::errors::Status;
#[derive(Debug, thiserror::Error, Status)]
#[error("The card was declined.")]
#[status(402)]
pub struct CardDeclined;
```
For additional error handling, use `app.errors()` inside your service provider's `register` method (which exposes the same `Errors` builder as an application's `with_errors`). For example, a billing package might suppress logging for expected declines, keep sensitive payment fields out of flashed old input, and render a structured JSON response for API requests:
```rust
use laravel::container::Registrar;
use laravel::foundation::ServiceProvider;
use laravel::prelude::*;
use serde_json::json;
impl ServiceProvider for BillingServiceProvider {
fn register(&self, app: &mut Registrar) {
let errors = app.errors();
errors.dont_report::();
errors.dont_flash(["card.number", "card.cvc"]);
errors.render(|error: &CardDeclined, request, status| {
if !request.wants_json() {
return None;
}
let body = json!({
"error": "card_declined",
"message": error.to_string(),
});
Some((status, Json(body)).into_response())
});
}
}
```
Consuming applications run their own `with_errors` callback after all providers, so application status mappings and renderers always take precedence over a package's defaults for the same error type.
## Logging
Packages can attach custom `tracing` layers (such as an error tracker or telemetry exporter) through `app.logging()`:
```rust
use laravel::container::Registrar;
fn register(&self, app: &mut Registrar) {
if app.config().section::().enabled {
app.logging().layer(telemetry_layer());
}
}
```
To learn how to build and filter custom `tracing` layers, check out [sending logs elsewhere](logging.md#sending-logs-elsewhere) in the logging guide.
## Checks at boot
Returning an error from `boot` prevents the application from starting, catching misconfigurations at deploy time rather than on the first request:
```rust
use laravel::container::Container;
use laravel::http::HeaderValue;
async fn boot(&self, app: &Container) -> laravel::Result<()> {
if !app.config().section::().header {
return Ok(());
}
let quotes = app.resolve::().await?;
if let Some(quote) = quotes
.all()
.iter()
.find(|quote| HeaderValue::from_str(quote).is_err())
{
return Err(laravel::abort_with(
500,
format!("The quote `{quote}` can't be sent in a header."),
));
}
Ok(())
}
```
The startup error names your provider so developers can immediately identify the failing package. Reserve `boot` for startup checks like this; keep registrations in `register` and service initialization in service factories.
## Testing packages
Place your package's integration tests in the `tests/` directory at the root of your package crate (for example, `tests/package.rs`). Because Cargo compiles files in `tests/` as separate crates, your tests exercise your package through its public API as a consuming application will.
If your tests need a Laravel feature your package does not enable in `[dependencies]` (such as `minijinja` for rendering `.html` views), add it under `[dev-dependencies]` in `Cargo.toml` so it is never pulled into applications that install your package:
```toml
# Cargo.toml
[dev-dependencies]
laravel-rust = { version = "0.1", default-features = false, features = ["minijinja"] }
```
Unlike an application, a package does not have a `src/app.rs` or `src/testing.rs`. Instead, define `configure` and `create` helpers in `tests/package.rs` that build a minimal test application with `for_testing(env!("CARGO_MANIFEST_DIR"))` and register your service provider, then pass `create` to `#[laravel::test(app = create)]`:
```rust
// tests/package.rs
use example_package::{InspireConfig, InspireServiceProvider};
use laravel::foundation::ApplicationBuilder;
use laravel::testing::prelude::*;
fn configure() -> ApplicationBuilder {
Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_providers(|providers| {
providers.add(InspireServiceProvider);
})
}
fn create() -> Application {
configure().create()
}
#[laravel::test(app = create)]
async fn the_package_route_and_assets_work(app: Application) {
let response = app.get("/inspire").await;
response.assert_ok();
assert!(response.header("x-inspiration").is_some());
app.get("/vendor/inspire/inspire.css")
.await
.assert_ok()
.assert_header("content-type", "text/css");
}
```
`#[laravel::test(app = create)]` calls `create()` for every test so each test boots an isolated application in the `testing` environment with a fresh encryption key and in-memory fallbacks for unset settings. Extract the helper rather than sharing a single booted `Application` across tests: giving each test its own application keeps sessions, caches, clocks, fakes, and configuration overrides isolated so tests run safely in parallel.
Returning an `ApplicationBuilder` from `configure()` gives you one place to set shared test defaults, such as `.with_envs(..)` for test environment variables, `.refresh_database()` for packages that ship [migrations](#migrations), or host application routes via `.with_routing(..)` to verify package middleware and injected services:
```rust
use example_package::{InspireServiceProvider, Quotes};
use laravel::container::Inject;
use laravel::foundation::ApplicationBuilder;
use laravel::testing::prelude::*;
fn configure() -> ApplicationBuilder {
Application::configure()
.for_testing(env!("CARGO_MANIFEST_DIR"))
.with_providers(|providers| {
providers.add(InspireServiceProvider);
})
.with_routing(|routing, _| {
routing.web(|route| {
route.get("/host", async |quotes: Inject| {
quotes.all().join("\n")
});
});
})
}
```
When your test suite grows across multiple files under `tests/`, Cargo compiles each file as its own crate. Move `configure()` and `create()` into `tests/common/mod.rs` as `pub` functions, declare `mod common;` in each test file, and pass `common::create` to `#[laravel::test]`:
```rust
// tests/middleware.rs
mod common;
use laravel::testing::prelude::*;
#[laravel::test(app = common::create)]
async fn web_responses_include_the_inspiration_header(app: Application) {
let response = app.get("/host").await;
response.assert_ok();
assert!(response.header("x-inspiration").is_some());
}
```
When a single test needs custom environment variables or configuration overrides, omit the `Application` argument on `#[laravel::test]` and build the customized application from `configure()` inside the test:
```rust
#[laravel::test]
async fn disabling_the_header_skips_the_middleware() {
let response = configure()
.with_envs([("INSPIRE_HEADER", "false")])
.create()
.get("/inspire")
.await;
response.assert_ok();
assert_eq!(response.header("x-inspiration"), None);
}
```
Similarly, to test a [boot check](#checks-at-boot) that should reject invalid configuration, call `.create().boot().await` directly and assert that booting fails:
```rust
#[laravel::test]
async fn invalid_quotes_stop_the_application_from_booting() {
let error = configure()
.with_config(|config, _| {
config.set(InspireConfig {
header: true,
quotes: vec!["Line one\nLine two".to_owned()],
});
})
.create()
.boot()
.await
.expect_err("booting should fail")
.to_string();
assert!(error.contains("can't be sent in a header"));
}
```
Run your package's test suite with `cargo test`. To explore additional HTTP assertions, authentication helpers, and subsystem fakes, check out the [testing guide](testing.md).