Skip to content
Welcome to the new era of Laravel. Today, Dec 1, at 10am PT / 1pm ET.Add it to your calendar

Package Development

Digging Deeper

Package Development

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, 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:

1cargo add laravel-rust --no-default-features
1cargo 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:

1# Cargo.toml
2[dependencies]
3laravel-rust = { version = "0.1", default-features = false, features = ["database"] }
1# Cargo.toml
2[dependencies]
3laravel-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:

1use laravel::config::{Config, Env};
2use laravel::container::{Container, Registrar};
3use laravel::foundation::ServiceProvider;
4 
5pub struct InspireServiceProvider;
6 
7impl ServiceProvider for InspireServiceProvider {
8 fn config(&self, config: &mut Config, env: &Env) {
9 // Register your package's default configuration...
10 }
11 
12 fn register(&self, app: &mut Registrar) {
13 // Register services, routes, views, commands, and more...
14 }
15 
16 async fn boot(&self, app: &Container) -> laravel::Result<()> {
17 // Validate configuration or run startup checks...
18 
19 Ok(())
20 }
21}
1use laravel::config::{Config, Env};
2use laravel::container::{Container, Registrar};
3use laravel::foundation::ServiceProvider;
4 
5pub struct InspireServiceProvider;
6 
7impl ServiceProvider for InspireServiceProvider {
8 fn config(&self, config: &mut Config, env: &Env) {
9 // Register your package's default configuration...
10 }
11 
12 fn register(&self, app: &mut Registrar) {
13 // Register services, routes, views, commands, and more...
14 }
15 
16 async fn boot(&self, app: &Container) -> laravel::Result<()> {
17 // Validate configuration or run startup checks...
18 
19 Ok(())
20 }
21}

All three methods are optional. Laravel invokes them in order:

  1. config runs on every provider to register default 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.

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 and embedded assets with_routing
middleware() Global, web, and api middleware with_middleware
views() View namespaces, engines, and shared data with_views
events() Event listeners with_events
commands() Console commands with_commands
schedule() Scheduled tasks with_schedule
ticks() Ticks that repeat in the server and queue workers with_ticks
errors() Custom error statuses and renderers with_errors
logging() Custom tracing layers with_logging
head() Default <head> tags with_head
migrations() Package migrations with_migrations
sessions(), cache(), mail(), queue(), features() Custom drivers such as a session store or cache store with_services

Packages cannot register authentication guards; 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:

1cargo add example-package
1cargo add example-package

Cargo resolves the latest compatible version and adds the crate under [dependencies] in your Cargo.toml:

1[dependencies]
2example-package = "0.1.0"
1[dependencies]
2example-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:

1cargo add example-package --features pdf
1cargo add example-package --features pdf

Or enable them directly in Cargo.toml:

1[dependencies]
2example-package = { version = "0.1.0", features = ["pdf"] }
1[dependencies]
2example-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:

1use laravel::Application;
2 
3Application::configure()
4 .with_providers(|providers| {
5 providers.add(example_package::InspireServiceProvider);
6 })
1use laravel::Application;
2 
3Application::configure()
4 .with_providers(|providers| {
5 providers.add(example_package::InspireServiceProvider);
6 })

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 struct by deriving Section, and annotate its fields with #[env(..)] attributes so applications can configure them through environment variables:

1use laravel::config::Section;
2 
3#[derive(Debug, Clone, Section)]
4pub struct InspireConfig {
5 #[env("INSPIRE_HEADER", default = true)]
6 pub header: bool,
7 #[env("INSPIRE_QUOTES", separator = "|")]
8 pub quotes: Vec<String>,
9}
1use laravel::config::Section;
2 
3#[derive(Debug, Clone, Section)]
4pub struct InspireConfig {
5 #[env("INSPIRE_HEADER", default = true)]
6 pub header: bool,
7 #[env("INSPIRE_QUOTES", separator = "|")]
8 pub quotes: Vec<String>,
9}

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:

1use laravel::config::{Config, Env};
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for InspireServiceProvider {
5 fn config(&self, config: &mut Config, env: &Env) {
6 config.discover(env!("CARGO_CRATE_NAME"), env);
7 }
8}
1use laravel::config::{Config, Env};
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for InspireServiceProvider {
5 fn config(&self, config: &mut Config, env: &Env) {
6 config.discover(env!("CARGO_CRATE_NAME"), env);
7 }
8}

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:

1// src/app.rs (in the consuming application)
2use example_package::InspireConfig;
3use laravel::Application;
4 
5Application::configure()
6 .with_config(|config, _| {
7 config.section_mut::<InspireConfig>().header = false;
8 })
1// src/app.rs (in the consuming application)
2use example_package::InspireConfig;
3use laravel::Application;
4 
5Application::configure()
6 .with_config(|config, _| {
7 config.section_mut::<InspireConfig>().header = false;
8 })

Services

Register your package's services inside register. For example, this registers a Quotes singleton initialized from InspireConfig:

1use laravel::container::Registrar;
2 
3#[derive(Clone)]
4pub struct Quotes {
5 quotes: Vec<String>,
6}
7 
8impl Quotes {
9 pub fn new(quotes: Vec<String>) -> Self {
10 Self { quotes }
11 }
12 
13 pub fn all(&self) -> &[String] {
14 &self.quotes
15 }
16}
17 
18fn register(&self, app: &mut Registrar) {
19 app.singleton(async |app| {
20 let config = app.config().section::<InspireConfig>();
21 
22 Ok(Quotes::new(config.quotes.clone()))
23 });
24}
1use laravel::container::Registrar;
2 
3#[derive(Clone)]
4pub struct Quotes {
5 quotes: Vec<String>,
6}
7 
8impl Quotes {
9 pub fn new(quotes: Vec<String>) -> Self {
10 Self { quotes }
11 }
12 
13 pub fn all(&self) -> &[String] {
14 &self.quotes
15 }
16}
17 
18fn register(&self, app: &mut Registrar) {
19 app.singleton(async |app| {
20 let config = app.config().section::<InspireConfig>();
21 
22 Ok(Quotes::new(config.quotes.clone()))
23 });
24}

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] and call app.discover to register all attribute-based services, command functions, listeners, and scheduled tasks in your crate at once:

1use laravel::config::Section;
2use laravel::container::singleton;
3 
4#[singleton]
5async fn quotes(config: Section<InspireConfig>) -> laravel::Result<Quotes> {
6 Ok(Quotes::new(config.quotes.clone()))
7}
8 
9fn register(&self, app: &mut Registrar) {
10 app.discover(env!("CARGO_CRATE_NAME"));
11}
1use laravel::config::Section;
2use laravel::container::singleton;
3 
4#[singleton]
5async fn quotes(config: Section<InspireConfig>) -> laravel::Result<Quotes> {
6 Ok(Quotes::new(config.quotes.clone()))
7}
8 
9fn register(&self, app: &mut Registrar) {
10 app.discover(env!("CARGO_CRATE_NAME"));
11}

Applications can inject your service with Inject<Quotes> or replace it in with_services.

Routes

Register routes in the web or api group through app.routing():

1use laravel::container::{Inject, Registrar};
2 
3fn register(&self, app: &mut Registrar) {
4 app.routing().web(|route| {
5 route.get("/inspire", inspire);
6 });
7}
8 
9/// `GET /inspire`: every quote, one per line.
10pub async fn inspire(quotes: Inject<Quotes>) -> String {
11 quotes.all().join("\n")
12}
1use laravel::container::{Inject, Registrar};
2 
3fn register(&self, app: &mut Registrar) {
4 app.routing().web(|route| {
5 route.get("/inspire", inspire);
6 });
7}
8 
9/// `GET /inspire`: every quote, one per line.
10pub async fn inspire(quotes: Inject<Quotes>) -> String {
11 quotes.all().join("\n")
12}

Make your route handlers pub. Because 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 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:

1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for InspireServiceProvider {
5 fn register(&self, app: &mut Registrar) {
6 if app.config().section::<InspireConfig>().header {
7 app.middleware().web(|web| {
8 web.append(AddInspiration);
9 });
10 }
11 }
12}
1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for InspireServiceProvider {
5 fn register(&self, app: &mut Registrar) {
6 if app.config().section::<InspireConfig>().header {
7 app.middleware().web(|web| {
8 web.append(AddInspiration);
9 });
10 }
11 }
12}

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::<AddInspiration>().

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:

1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.views().namespace("inspire", laravel::embed!("resources/views"));
5}
1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.views().namespace("inspire", laravel::embed!("resources/views"));
5}

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:

1cargo add --dev laravel-rust --no-default-features --features minijinja
1cargo 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/<namespace>/<path>:

1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.routing().assets("inspire", laravel::embed!("public"));
5}
1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.routing().assets("inspire", laravel::embed!("public"));
5}

Reference package assets using vendor_asset in Rust or templates:

1<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">
1<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">

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):

1import { defineConfig } from 'vite';
2 
3export default defineConfig({
4 base: '/vendor/dashboard/',
5 publicDir: false,
6 build: {
7 outDir: 'dist',
8 cssCodeSplit: false,
9 rolldownOptions: {
10 input: 'resources/js/app.js',
11 output: {
12 entryFileNames: 'app.js',
13 assetFileNames: '[name][extname]',
14 codeSplitting: false,
15 },
16 },
17 },
18});
1import { defineConfig } from 'vite';
2 
3export default defineConfig({
4 base: '/vendor/dashboard/',
5 publicDir: false,
6 build: {
7 outDir: 'dist',
8 cssCodeSplit: false,
9 rolldownOptions: {
10 input: 'resources/js/app.js',
11 output: {
12 entryFileNames: 'app.js',
13 assetFileNames: '[name][extname]',
14 codeSplitting: false,
15 },
16 },
17 },
18});

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

1fn register(&self, app: &mut Registrar) {
2 app.routing().assets("dashboard", laravel::embed!("dist"));
3}
1fn register(&self, app: &mut Registrar) {
2 app.routing().assets("dashboard", laravel::embed!("dist"));
3}
1<link rel="stylesheet" href="{{ vendor_asset("dashboard", "style.css") }}">
2<script type="module" src="{{ vendor_asset("dashboard", "app.js") }}"></script>
1<link rel="stylesheet" href="{{ vendor_asset("dashboard", "style.css") }}">
2<script type="module" src="{{ vendor_asset("dashboard", "app.js") }}"></script>

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:

1[package]
2include = ["src/**", "resources/views/**", "dist/**", "Cargo.toml", "README.md", "LICENSE"]
1[package]
2include = ["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):

1npx vite build
2cargo package --list
1npx vite build
2cargo package --list

Migrations

Packages that store database tables can ship migrations and register them via app.migrations(). Running migrate in an application executes package and application migrations together in filename order:

1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.migrations().add(laravel::db::migrations!("database/migrations"));
5}
1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 app.migrations().add(laravel::db::migrations!("database/migrations"));
5}

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:

1// build.rs
2fn main() {
3 println!("cargo::rerun-if-changed=database/migrations");
4}
1// build.rs
2fn main() {
3 println!("cargo::rerun-if-changed=database/migrations");
4}

Commands and scheduled tasks

Packages can register their own console 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<T>:

1use laravel::console::{Console, command};
2use laravel::container::Inject;
3 
4/// List every inspiring quote.
5#[command("inspire:list")]
6pub async fn list_quotes(console: &mut Console, quotes: Inject<Quotes>) {
7 for quote in quotes.all() {
8 console.line(quote);
9 }
10}
1use laravel::console::{Console, command};
2use laravel::container::Inject;
3 
4/// List every inspiring quote.
5#[command("inspire:list")]
6pub async fn list_quotes(console: &mut Console, quotes: Inject<Quotes>) {
7 for quote in quotes.all() {
8 console.line(quote);
9 }
10}

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 explicitly with app.commands().add::<ListQuotes>()). 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 inside your service provider's register method via app.schedule():

1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for BillingServiceProvider {
5 fn register(&self, app: &mut Registrar) {
6 app.schedule()
7 .command("billing:sync-invoices")
8 .daily_at("08:00");
9 }
10}
1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4impl ServiceProvider for BillingServiceProvider {
5 fn register(&self, app: &mut Registrar) {
6 app.schedule()
7 .command("billing:sync-invoices")
8 .daily_at("08:00");
9 }
10}

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)] so consuming applications do not have to map each error manually:

1use laravel::errors::Status;
2 
3#[derive(Debug, thiserror::Error, Status)]
4#[error("The card was declined.")]
5#[status(402)]
6pub struct CardDeclined;
1use laravel::errors::Status;
2 
3#[derive(Debug, thiserror::Error, Status)]
4#[error("The card was declined.")]
5#[status(402)]
6pub 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:

1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3use laravel::prelude::*;
4use serde_json::json;
5 
6impl ServiceProvider for BillingServiceProvider {
7 fn register(&self, app: &mut Registrar) {
8 let errors = app.errors();
9 
10 errors.dont_report::<CardDeclined>();
11 errors.dont_flash(["card.number", "card.cvc"]);
12 
13 errors.render(|error: &CardDeclined, request, status| {
14 if !request.wants_json() {
15 return None;
16 }
17 
18 let body = json!({
19 "error": "card_declined",
20 "message": error.to_string(),
21 });
22 
23 Some((status, Json(body)).into_response())
24 });
25 }
26}
1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3use laravel::prelude::*;
4use serde_json::json;
5 
6impl ServiceProvider for BillingServiceProvider {
7 fn register(&self, app: &mut Registrar) {
8 let errors = app.errors();
9 
10 errors.dont_report::<CardDeclined>();
11 errors.dont_flash(["card.number", "card.cvc"]);
12 
13 errors.render(|error: &CardDeclined, request, status| {
14 if !request.wants_json() {
15 return None;
16 }
17 
18 let body = json!({
19 "error": "card_declined",
20 "message": error.to_string(),
21 });
22 
23 Some((status, Json(body)).into_response())
24 });
25 }
26}

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():

1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 if app.config().section::<TelemetryConfig>().enabled {
5 app.logging().layer(telemetry_layer());
6 }
7}
1use laravel::container::Registrar;
2 
3fn register(&self, app: &mut Registrar) {
4 if app.config().section::<TelemetryConfig>().enabled {
5 app.logging().layer(telemetry_layer());
6 }
7}

To learn how to build and filter custom tracing layers, check out 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:

1use laravel::container::Container;
2use laravel::http::HeaderValue;
3 
4async fn boot(&self, app: &Container) -> laravel::Result<()> {
5 if !app.config().section::<InspireConfig>().header {
6 return Ok(());
7 }
8 
9 let quotes = app.resolve::<Quotes>().await?;
10 
11 if let Some(quote) = quotes
12 .all()
13 .iter()
14 .find(|quote| HeaderValue::from_str(quote).is_err())
15 {
16 return Err(laravel::abort_with(
17 500,
18 format!("The quote `{quote}` can't be sent in a header."),
19 ));
20 }
21 
22 Ok(())
23}
1use laravel::container::Container;
2use laravel::http::HeaderValue;
3 
4async fn boot(&self, app: &Container) -> laravel::Result<()> {
5 if !app.config().section::<InspireConfig>().header {
6 return Ok(());
7 }
8 
9 let quotes = app.resolve::<Quotes>().await?;
10 
11 if let Some(quote) = quotes
12 .all()
13 .iter()
14 .find(|quote| HeaderValue::from_str(quote).is_err())
15 {
16 return Err(laravel::abort_with(
17 500,
18 format!("The quote `{quote}` can't be sent in a header."),
19 ));
20 }
21 
22 Ok(())
23}

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:

1# Cargo.toml
2[dev-dependencies]
3laravel-rust = { version = "0.1", default-features = false, features = ["minijinja"] }
1# Cargo.toml
2[dev-dependencies]
3laravel-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)]:

1// tests/package.rs
2use example_package::{InspireConfig, InspireServiceProvider};
3use laravel::foundation::ApplicationBuilder;
4use laravel::testing::prelude::*;
5 
6fn configure() -> ApplicationBuilder {
7 Application::configure()
8 .for_testing(env!("CARGO_MANIFEST_DIR"))
9 .with_providers(|providers| {
10 providers.add(InspireServiceProvider);
11 })
12}
13 
14fn create() -> Application {
15 configure().create()
16}
17 
18#[laravel::test(app = create)]
19async fn the_package_route_and_assets_work(app: Application) {
20 let response = app.get("/inspire").await;
21 
22 response.assert_ok();
23 assert!(response.header("x-inspiration").is_some());
24 
25 app.get("/vendor/inspire/inspire.css")
26 .await
27 .assert_ok()
28 .assert_header("content-type", "text/css");
29}
1// tests/package.rs
2use example_package::{InspireConfig, InspireServiceProvider};
3use laravel::foundation::ApplicationBuilder;
4use laravel::testing::prelude::*;
5 
6fn configure() -> ApplicationBuilder {
7 Application::configure()
8 .for_testing(env!("CARGO_MANIFEST_DIR"))
9 .with_providers(|providers| {
10 providers.add(InspireServiceProvider);
11 })
12}
13 
14fn create() -> Application {
15 configure().create()
16}
17 
18#[laravel::test(app = create)]
19async fn the_package_route_and_assets_work(app: Application) {
20 let response = app.get("/inspire").await;
21 
22 response.assert_ok();
23 assert!(response.header("x-inspiration").is_some());
24 
25 app.get("/vendor/inspire/inspire.css")
26 .await
27 .assert_ok()
28 .assert_header("content-type", "text/css");
29}

#[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, or host application routes via .with_routing(..) to verify package middleware and injected services:

1use example_package::{InspireServiceProvider, Quotes};
2use laravel::container::Inject;
3use laravel::foundation::ApplicationBuilder;
4use laravel::testing::prelude::*;
5 
6fn configure() -> ApplicationBuilder {
7 Application::configure()
8 .for_testing(env!("CARGO_MANIFEST_DIR"))
9 .with_providers(|providers| {
10 providers.add(InspireServiceProvider);
11 })
12 .with_routing(|routing, _| {
13 routing.web(|route| {
14 route.get("/host", async |quotes: Inject<Quotes>| {
15 quotes.all().join("\n")
16 });
17 });
18 })
19}
1use example_package::{InspireServiceProvider, Quotes};
2use laravel::container::Inject;
3use laravel::foundation::ApplicationBuilder;
4use laravel::testing::prelude::*;
5 
6fn configure() -> ApplicationBuilder {
7 Application::configure()
8 .for_testing(env!("CARGO_MANIFEST_DIR"))
9 .with_providers(|providers| {
10 providers.add(InspireServiceProvider);
11 })
12 .with_routing(|routing, _| {
13 routing.web(|route| {
14 route.get("/host", async |quotes: Inject<Quotes>| {
15 quotes.all().join("\n")
16 });
17 });
18 })
19}

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]:

1// tests/middleware.rs
2mod common;
3 
4use laravel::testing::prelude::*;
5 
6#[laravel::test(app = common::create)]
7async fn web_responses_include_the_inspiration_header(app: Application) {
8 let response = app.get("/host").await;
9 
10 response.assert_ok();
11 assert!(response.header("x-inspiration").is_some());
12}
1// tests/middleware.rs
2mod common;
3 
4use laravel::testing::prelude::*;
5 
6#[laravel::test(app = common::create)]
7async fn web_responses_include_the_inspiration_header(app: Application) {
8 let response = app.get("/host").await;
9 
10 response.assert_ok();
11 assert!(response.header("x-inspiration").is_some());
12}

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:

1#[laravel::test]
2async fn disabling_the_header_skips_the_middleware() {
3 let response = configure()
4 .with_envs([("INSPIRE_HEADER", "false")])
5 .create()
6 .get("/inspire")
7 .await;
8 
9 response.assert_ok();
10 assert_eq!(response.header("x-inspiration"), None);
11}
1#[laravel::test]
2async fn disabling_the_header_skips_the_middleware() {
3 let response = configure()
4 .with_envs([("INSPIRE_HEADER", "false")])
5 .create()
6 .get("/inspire")
7 .await;
8 
9 response.assert_ok();
10 assert_eq!(response.header("x-inspiration"), None);
11}

Similarly, to test a boot check that should reject invalid configuration, call .create().boot().await directly and assert that booting fails:

1#[laravel::test]
2async fn invalid_quotes_stop_the_application_from_booting() {
3 let error = configure()
4 .with_config(|config, _| {
5 config.set(InspireConfig {
6 header: true,
7 quotes: vec!["Line one\nLine two".to_owned()],
8 });
9 })
10 .create()
11 .boot()
12 .await
13 .expect_err("booting should fail")
14 .to_string();
15 
16 assert!(error.contains("can't be sent in a header"));
17}
1#[laravel::test]
2async fn invalid_quotes_stop_the_application_from_booting() {
3 let error = configure()
4 .with_config(|config, _| {
5 config.set(InspireConfig {
6 header: true,
7 quotes: vec!["Line one\nLine two".to_owned()],
8 });
9 })
10 .create()
11 .boot()
12 .await
13 .expect_err("booting should fail")
14 .to_string();
15 
16 assert!(error.contains("can't be sent in a header"));
17}

Run your package's test suite with cargo test. To explore additional HTTP assertions, authentication helpers, and subsystem fakes, check out the testing guide.