Looking to hire Laravel developers? Try LaraJobs

laravel-installer maintained by smartrahat

Description
A reusable and extensible Laravel application installer.
Author
Last update
2026/11/24 03:09 (dev-main)
License
Downloads
2

Comments
comments powered by Disqus

SmartRahat Laravel Installer

SmartRahat Laravel Installer is a reusable web-based installation package for Laravel applications. It provides a guided installation process for environment configuration, database connection, migrations, seeders, administrator creation, optional mail configuration, and installation finalization.

The package is intentionally general purpose: it installs any Laravel 12 or 13 application, writes the .env file, tests and configures the database, runs migrations and seeders, creates the first administrator and optionally configures SMTP. It suits SaaS applications, commercial Laravel projects, internal business applications, client projects and custom Laravel products alike, and host applications can add their own installation steps without changing the package.


Requirements

  • PHP 8.3 or newer, below PHP 9
  • Laravel 12 or Laravel 13
  • PHP extensions: ctype, curl, dom, fileinfo, filter, hash, mbstring, openssl, pcre, pdo, session, tokenizer, xml
  • A PDO driver for the selected database (pdo_mysql, pdo_pgsql or pdo_sqlite)
  • Writable storage/, bootstrap/cache/ and .env

Required extensions and directories are configurable, see Configuration.

Supported versions

Laravel PHP Status
12.x 8.3+ Supported, covered by the test suite and runtime-tested
13.x 8.3+ Supported, covered by the test suite and runtime-tested

Laravel 10 and Laravel 11 are not supported. composer.json requires php: ^8.3 and illuminate/support: ^12.0|^13.0, and the installer's own server-requirements page refuses to continue on PHP older than 8.3.

Composer constraints alone do not prove runtime compatibility, so both supported lines are also covered by the package's PHPUnit suite and have been exercised through complete installations in real Laravel 12 and Laravel 13 applications.


Installation

composer require smartrahat/laravel-installer

The service provider is auto-discovered. Publish the configuration file:

php artisan vendor:publish --tag=laravel-installer-config

Views can be overridden by creating files under resources/views/vendor/laravel-installer/.

Installer middleware

InstallerMiddleware sends visitors to the installer while the application is not installed, and sends them away from the installer after installation.

Laravel 12 / 13 (bootstrap/app.php):

use SmartRahat\LaravelInstaller\Middleware\InstallerMiddleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        InstallerMiddleware::class,
    ]);
})

InstallerMiddleware is not registered automatically. You can apply it to a smaller group of routes instead of the whole web group, and health-check or monitoring endpoints (for example /up) may need to be exempted so they keep responding while the application is not installed. In that case protect every application route that must not be reachable before installation.

Installer routes are always protected by RedirectIfInstalled, so the wizard itself cannot be reopened once the installation marker exists, even if the host application does not register InstallerMiddleware.

Visit the installer

https://example.com/install

How it works

  1. Welcome – introduction.
  2. Requirements – PHP version, extensions and directory permissions.
  3. Environment – application name, URL, timezone, environment, debug mode, .env writing and application key generation.
  4. Database – driver, credentials, optional automatic database creation and a connection test.
  5. Migrations – Laravel migrations, executed only after a successful connection test.
  6. Seeders – the seeders configured by the host application.
  7. Administrator – the first administrator account.
  8. Custom steps – host application steps, in registration order.
  9. Mail – optional SMTP configuration and test email.
  10. Finish – summary, installation marker and redirect.

Progress is stored in a JSON file (laravel-installer.progress_file) so a wizard can be resumed. Only the installation marker decides whether the application is installed.

Routes

All routes are prefixed with laravel-installer.route_prefix (default install) and named with laravel-installer.:

Method Path Name
GET / welcome
GET /requirements requirements
GET/POST /environment environment, environment.store
GET/POST /database database, database.store
POST /database/test database.test
GET/POST /migrations migrations, migrations.run
GET/POST /seeders seeders, seeders.run
GET/POST /administrator administrator, administrator.store
GET/POST /steps/{step} step.show, step.store
GET/POST /mail mail, mail.store
POST /mail/test, /mail/skip mail.test, mail.skip
GET/POST /finish finalize, finalize.store

Each stage after requirements is guarded: visiting a later stage before the previous stages are complete redirects to the first incomplete stage.


Configuration

Published to config/laravel-installer.php.

Key Default Purpose
route_prefix install URL prefix for all installer routes
installation_marker storage/app/installed JSON file that marks the app installed
redirect_after_installation / Destination after install and for installer routes afterwards
env.path null (base_path('.env')) .env file written by the installer
env.generate_app_key true Generate APP_KEY when it is empty
key_file storage/framework/installer-app-key Temporary key used before .env has a key
progress_file storage/framework/installer-progress.json Wizard progress
requirements.php_version 8.3.0 Minimum PHP version
requirements.extensions see config Required extensions
requirements.directories storage, bootstrap/cache Directories that must be writable
database.drivers mysql, mariadb, pgsql, sqlite Offered drivers
database.default_ports 3306 / 5432 Suggested ports
database.allow_database_creation true Show/create the "create database" option
database.connection_timeout 5 Connection timeout in seconds
database.sqlite_path database/database.sqlite Suggested SQLite path
database.allow_external_sqlite_path false Allow absolute SQLite paths outside the application
migrations.path null Optional migrations path
migrations.options [] Extra migrate options
seeders [] Seeder class names
administrator.enabled true Enable the administrator stage
administrator.creator null Custom creator class or closure
administrator.model App\Models\User Default creator model
administrator.*_attribute name, email, password Default creator attributes
mail.enabled true Enable the mail stage
mail.optional true Mark it optional and allow skipping
mail.default_port 587 Suggested SMTP port
mail.timeout 10 SMTP connection timeout in seconds
mail.test_recipients [] Extra addresses allowed to receive test emails
mail.allow_arbitrary_test_recipient false Allow any test recipient (insecure)
throttle.test 10,1 Rate limit for the connection-test routes (own bucket)
throttle.state 30,1 Rate limit for state-changing routes (own bucket)
sensitive_fields see config Fields removed from flashed old input
sensitive_field_pattern see config Field-name pattern removed from old input
steps [] Custom step classes

Route prefix, marker and redirect

'route_prefix' => 'setup',
'installation_marker' => storage_path('app/setup-complete'),
'redirect_after_installation' => '/admin',

Changing installation_marker after installation makes the application look uninstalled. Keep it stable in production.

Installer middleware

See Installer middleware. This is what redirects normal application routes to /install before installation.


Environment file handling

SmartRahat\LaravelInstaller\Support\EnvWriter updates .env safely:

  • Existing variables that are not being changed are preserved exactly, including comments and blank lines.
  • Keys are updated in place and never duplicated.
  • Values containing spaces, quotes, #, $ or other special characters are quoted and escaped, and round-trip correctly.
  • Empty values are written as KEY=.
  • Values are written to a temporary file first and moved into place, so a failed write cannot truncate .env.
  • When .env does not exist, .env.example is used as the starting point.
  • Existing file permissions are preserved.

Values are never exposed in logs. Password fields are blank on error so credentials are not echoed back into the HTML.

Application key

The installer routes use sessions and CSRF protection, which require APP_KEY even before installation. When APP_KEY is empty:

  1. A temporary key is generated and stored in key_file.
  2. Installer requests use it.
  3. The environment step writes that same key to .env.
  4. The temporary key file is deleted when installation finishes.

An existing APP_KEY is never regenerated.

Sessions and rate limiting before migrations

Fresh Laravel 12/13 applications default to SESSION_DRIVER=database and CACHE_STORE=database, but neither the sessions table nor the cache table exists before migrations. Until the application is installed:

  • the installer falls back to the file session driver;
  • the installer's rate limiter uses a dedicated file cache store named laravel-installer-limiter, in storage/framework/cache/laravel-installer-limiter.

Both fallbacks only redirect the installer's own settings. The host application's session and cache configuration is otherwise untouched: in particular cache.default still points at the database store, the application's own file store is neither reused nor modified, and only cache.limiter is changed, so nothing else in the application changes behaviour. If storage is relocated or symlinked, set laravel-installer.limiter_store_path to a path that does not exist yet.

The rate-limiter fallback matters because every state-changing installer route and both connection-test routes are throttled, and they run long before the wizard's migration step creates the cache table. Without it, a fresh installation would fail before it could write anything.

The file store is used rather than the array store because the array store is per request: it would keep the installer working but could never count requests across separate HTTP requests, so the configured limit would never be reached.

The installer only claims a limiter directory it created itself. If laravel-installer.limiter_store_path points at a directory that already exists before the installer uses it, that directory belongs to the host: it is never given the installer's sentinel, never used for counters and never deleted, and the limiter falls back to the array store. Point the option at a path that does not exist yet when you relocate it.

Two limitations follow from the storage used:

  • Best-effort counters. Laravel's file cache updates a counter by reading, incrementing and writing the counter file, so simultaneous requests can occasionally overwrite one another. The limiter is a coarse pre-installation guard, not exact atomic accounting.
  • One filesystem, one node. Counters live on the local disk of the server that handled the request. On a multi-server deployment every node counts only its own traffic, so the limit is per node and is not synchronized between nodes; it is not a distributed rate limiter.

If the limiter directory cannot be created or written, the installer falls back to the array store, so a storage problem never turns a throttled request into an HTTP 500. The same fallback applies when the configured directory already exists, because the installer does not take ownership of it. That fallback is degraded protection: it preserves availability, but cross-request rate limits are not enforced while it is active.

Once the installation marker exists, neither fallback is applied and the configured drivers are used again. Successful finalization removes a limiter directory the installer created, together with its ownership record, and never removes a directory it did not create; a failure to remove its own directory never interrupts finalization.

If the application has a cached config (bootstrap/cache/config.php), clear it before installing: php artisan config:clear.


Database configuration

Supported drivers: MySQL, MariaDB, PostgreSQL and SQLite.

For MySQL, MariaDB and PostgreSQL the form asks for driver, host, port, database name, username and password. SQLite asks only for a database file path (relative to the application root, or absolute); the file is created when it does not exist.

SQLite paths are confined to the application directory by default:

  • Relative paths are resolved against the application root and may not use .. to leave it.

  • Absolute local paths outside the application are rejected unless database.allow_external_sqlite_path is enabled.

  • Network paths (\\server\share\file.sqlite, //server/share/file.sqlite) and stream wrappers (file://...) are always rejected, because on Windows they can open an outbound SMB connection and leak NTLM credentials.

  • Symlinks are resolved, and a link that points outside the permitted directory is rejected.

  • A failed connection test never leaves a newly created empty database file behind, and never deletes a database file that already existed.

  • Connection test – the supplied values are tested with PDO before anything is saved. Invalid credentials, unreachable servers, missing databases and SQLite file problems produce clear, credential-free messages.

  • Automatic database creation – optional, configurable with database.allow_database_creation. For MySQL/MariaDB the driver requires permission to create databases; PostgreSQL connects to postgres and checks pg_database first. Only names made of ASCII letters, numbers and underscores can be created automatically.

  • MariaDB is saved as DB_CONNECTION=mysql because Laravel's mysql driver works with MariaDB on Laravel 12 and 13, so no separate connection is required.

  • Database settings are only written to .env after a successful connection test.

  • Migrations run through php artisan migrate --force after the connection test and cannot run twice through the wizard.

  • Seeders are executed with php artisan db:seed --class=... --force. Configure them with laravel-installer.seeders; nothing is assumed by default.

'seeders' => [
    Database\Seeders\DatabaseSeeder::class,
],

Seeders run in the configured order. If one fails midway, the stage is not marked complete and retrying re-runs the earlier seeders; make seeders idempotent (firstOrCreate, updateOrCreate) where retries are possible.

Unix sockets are not supported by the connection form; set DB_HOST to a socket path in .env manually if needed.


Administrator setup

By default the installer creates the account with the configured model:

'administrator' => [
    'enabled' => true,
    'creator' => null,
    'model' => App\Models\User::class,
    'name_attribute' => 'name',
    'email_attribute' => 'email',
    'password_attribute' => 'password',
],

The password is hashed with Laravel's Hash facade. Creation errors are shown as a generic message and only the exception class is logged.

Custom administrator creation

Implement SmartRahat\LaravelInstaller\Contracts\AdministratorCreator when the application needs roles, profiles, verification tokens or another model:

namespace App\Installer;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use SmartRahat\LaravelInstaller\Contracts\AdministratorCreator;
use Throwable;

class AdministratorCreator implements AdministratorCreator
{
    public function create(array $data): void
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $user->assignRole('administrator');
    }
}
'administrator' => [
    'creator' => App\Installer\AdministratorCreator::class,
],

A closure is also accepted, but closures cannot be used with php artisan config:cache:

'creator' => function (array $data) {
    // create the administrator
},

Set 'enabled' => false when the application creates administrators another way; the stage is then skipped.


Mail (SMTP) configuration

The mail stage is optional and can always be skipped.

Fields: mailer (SMTP, Sendmail, Log), SMTP host, port, username, password, encryption (none, TLS, SSL), from address and from name.

  • Valid settings are written to .env.
  • Send Test Email sends a test without saving.
  • Skipping marks the stage complete and installation continues.
  • Credentials are never pre-filled or displayed. Password input is cleared after errors; re-enter it when saving or testing again.
  • SMTP connections use an explicit timeout (mail.timeout, 10 seconds by default). Raise it for a slow private SMTP server; it is never unbounded.

Test email recipients

The installer must not act as an open relay. A test email is only sent to:

  • the administrator address created during this installation, or
  • an address listed in laravel-installer.mail.test_recipients.

The submitted test_email field is not treated as authorization. Set mail.allow_arbitrary_test_recipient to true only in a development environment where that risk is understood.

With administrator.enabled set to false the installer never records an administrator address, and resuming the wizard in a new session loses one recorded earlier. In both cases only mail.test_recipients remains, so add the address you want to test with there when SMTP testing is required. The mail page shows the currently trusted addresses, or a hint when there are none.


Custom installation steps

Custom steps are plain classes implementing SmartRahat\LaravelInstaller\Contracts\InstallerStep. They run after the administrator stage and before the mail stage, in registration order.

namespace App\Installer;

use Illuminate\Http\Request;
use SmartRahat\LaravelInstaller\Exceptions\StepFailedException;
use SmartRahat\LaravelInstaller\Steps\AbstractStep;

class ApiCredentialsStep extends AbstractStep
{
    public function key(): string
    {
        return 'api';
    }

    public function title(): string
    {
        return 'API Credentials';
    }

    public function description(): string
    {
        return 'Connect this installation to your API account.';
    }

    public function view(): string
    {
        return 'installer.api';
    }

    public function handle(Request $request): void
    {
        $validated = $request->validate([
            'api_key' => ['required', 'string', 'max:255'],
        ]);

        if (! $this->verify($validated['api_key'])) {
            throw StepFailedException::because(
                'That API key could not be verified.'
            );
        }
    }
}

Register it in the configuration:

'steps' => [
    App\Installer\ApiCredentialsStep::class,
],

or at runtime, for example in a service provider:

use SmartRahat\LaravelInstaller\InstallerStepRegistry;

$this->app->make(InstallerStepRegistry::class)
    ->register(new App\Installer\ApiCredentialsStep());

The step key must be URL safe: letters, numbers, - and _ (the route uses [A-Za-z0-9_-]+). Duplicate keys overwrite earlier steps.

The view receives $step, $steps, $currentStep, $completedSteps and $previousStep:

@extends('laravel-installer::layouts.app')

@section('content')
    <div class="installer-card">
        @include('laravel-installer::partials.progress')
        @include('laravel-installer::partials.alerts')

        <h1>{{ $step->title() }}</h1>

        <form method="POST" action="{{ route('laravel-installer.step.store', ['step' => $step->key()]) }}">
            @csrf

            <div class="form-group">
                <label for="api_key">API Key</label>
                <input type="password" id="api_key" name="api_key" value="">
            </div>

            <div class="form-footer">
                <button type="submit" class="btn-primary">Continue</button>
            </div>
        </form>
    </div>
@endsection

Validation inside handle() returns normal Laravel validation errors. Throwing StepFailedException shows its message and keeps the user on the step. Any other exception shows a generic message and logs only the exception class.

If the step's form submits secrets, also implement SmartRahat\LaravelInstaller\Contracts\ExposesSensitiveFields and list those field names. They are then removed from flashed old input when validation fails, exactly like db_password and mail_password:

use SmartRahat\LaravelInstaller\Contracts\ExposesSensitiveFields;

class ApiCredentialsStep extends AbstractStep implements ExposesSensitiveFields
{
    public function sensitiveFields(): array
    {
        return ['api_key'];
    }
}

Fields are matched by exact name and by the configurable sensitive_field_pattern, which is applied case-insensitively and matches both bare names and names ending in _password, _passwd, _secret, _token, _api_key or _private_key (for example password, api_key, db_password, smtp_secret, vendor_api_key). Laravel's own _token CSRF field is intentionally excluded from the pattern and is kept as old input.

Because the pattern is a default, a step that does not implement the interface still never flashes a field ending in those forms. Sensitive fields are removed from flashed _old_input before the session is persisted, so they are not available as persisted old input to the next request.

If sensitiveFields() throws, returns unexpected data or names a step that does not exist, the package falls back to this default protection; a defective step cannot disable it or turn sanitisation into a server error.

A step without custom fields can extend AbstractStep and keep the default generic view.


Installation marker and reinstalling

storage/app/installed contains:

{
    "installed": true,
    "installed_at": "2026-11-22T10:00:00+00:00",
    "installer_version": "1.0.0"
}

The marker is written atomically and treated as installed only when it is valid JSON with installed === true, a non-empty installed_at and a non-empty installer_version.

  • Installer routes redirect to redirect_after_installation after installation.
  • Application routes are readable again.
  • Wizard progress and the temporary key file are removed.

To reinstall during development, delete the marker and the progress file, then clear the cached config. Never expose a way to do this in production.


Security notes

The installer is public until installation is complete

The package ships a public web wizard. Until the installation marker exists, anyone who can reach the route can use it — there is no authentication or authorization callback. An unauthorized visitor could:

  • configure the application's environment (name, URL, environment, debug mode, APP_KEY) and therefore how the application behaves;
  • configure its database connection;
  • run migrations and seeders;
  • create the first administrator account, taking over the application.

Never leave an uninstalled application reachable on the public internet. Protect the installer while it is online, using deployment-level controls. The database and SMTP test endpoints cause the server to attempt outbound connections to host addresses and ports supplied during setup, so host-level access controls and network restrictions should be applied as well.

  • HTTP Basic Authentication in the web server or reverse proxy (nginx auth_basic, Apache Require valid-user).
  • IP allow-listing, so only your address can reach /install.
  • Maintenance mode while installing, for example php artisan down --secret="a-long-random-string" and browsing /install?secret=a-long-random-string (--allow=<ip> also works).
  • A private network, VPN or SSH tunnel that exposes the site only to you.

Install immediately after deploying, then remove or disable the installer:

composer remove smartrahat/laravel-installer

Or keep the package installed and remove its route registration and InstallerMiddleware from the application. Installer routes also refuse to run once the marker exists, but removing the package is the strongest guarantee. Do not commit .env, the marker or the progress file.

The installer middleware is optional and not auto-registered

InstallerMiddleware is not registered by the package. The host application must add it (see Installer middleware) if application routes should redirect to the wizard before installation. Without it, those routes remain reachable while the application is uninstalled.

When you do register it, exempt health-check and monitoring endpoints (for example /up or /health) so load balancers still see a healthy application during installation — or apply the middleware only to the route group that must be protected instead of the whole web group.

Single operator, no step locking

The wizard assumes one operator installing one application. It has no per-step locking, so two concurrent browser sessions can interleave and overwrite each other's progress. Step-level locking and an optional authorization callback are deferred to v1.1.

Other protections

  • All mutations are POST requests protected by CSRF.
  • All input is validated server-side; browser validation is never trusted.
  • Passwords (password, password_confirmation, db_password, mail_password, and any field declared through ExposesSensitiveFields) are removed from flashed _old_input before the session is persisted, so they are not available as old input to the next request, in error messages or in pre-filled form fields. They are also never written to logs.
  • Administrator passwords are hashed; custom creators must hash them too.
  • .env writes are atomic and preserve unrelated values.
  • .env values are quoted and escaped, preventing value injection.
  • Installer routes are blocked by the marker after installation.
  • Errors are generic to the user; only exception classes are logged.
  • Database and SMTP test endpoints and state-changing routes are rate limited in two independent buckets: throttle.test (10 requests per minute by default) for the connection tests and throttle.state (30 per minute) for state changes. Each group has its own cache key prefix, so traffic to one never consumes the other's budget. While the application is not installed the limiter uses a dedicated file cache store (cache.limiter), so counters survive between requests without a database cache table; cache.default and the application's own file store are left unchanged. If that directory cannot be written, or if the configured path already exists and therefore belongs to the host, the limiter degrades to the array store: the installer stays available but cross-request limits are not enforced. The file store is local to one server and its counter updates are best-effort under concurrency, so the limit is per node rather than distributed, and finalization removes only a limiter directory the installer created itself.
  • SMTP connections use an explicit timeout (mail.timeout, 10 seconds).
  • Test emails only go to the administrator address from this installation or to mail.test_recipients.
  • SQLite files are confined to the application directory unless explicitly opted out, and network paths are always rejected.

Recommended production steps after installation:

  1. Set APP_ENV=production and APP_DEBUG=false.
  2. Restrict the database user's privileges to what the application needs.
  3. Ensure .env is not web-accessible and is not committed.
  4. Remove smartrahat/laravel-installer from composer.json (or remove its routes and middleware registration) if the application is distributed publicly.
  5. Run php artisan config:cache and php artisan route:cache if desired.
  6. Delete the installer progress file and any temporary key file.

Troubleshooting

419 Page Expired – the session or CSRF token could not be used. Check that storage/framework/sessions is writable, .env has a valid APP_KEY, and no cached config points at an unmigrated database session table.

"The environment settings could not be written" – .env or its directory is not writable by the web server user. Check permissions.

Requirements page blocks Continue – fix the failed PHP extension or make storage/ and bootstrap/cache/ writable, then reload.

Changes to config are ignored – a cached config exists. Run php artisan config:clear before installing.

Redirect loop – check that route_prefix is correct and that the marker file is readable by the application.

Database does not exist – create it manually or enable automatic database creation and give the user CREATE permission.

Database driver missing – install pdo_mysql, pdo_pgsql or pdo_sqlite.

SQLite file cannot be created – the database directory must exist and be writable by the web server user.

SQLite path rejected – the path leaves the application directory, is a network (UNC) path, or points at a symlink outside it. Use a path inside the application, or enable database.allow_external_sqlite_path for an external local path (network paths stay blocked).

Mail test fails – verify host, port, encryption and credentials; some providers require an app-specific password. Check the application log for the exception class. Increase mail.timeout for slow private SMTP servers.

"Test emails can only be sent to the administrator address…" – add the address to mail.test_recipients, or send the test to the administrator email created during this installation. This is also the expected message when administrator.enabled is false, or when the wizard was resumed in a new session: no administrator address is trusted then, so configure mail.test_recipients.

Custom step missing – confirm the class is listed in laravel-installer.steps, implements InstallerStep, and that the config is not cached.

Marker exists but the app still redirects to the installer – the marker is invalid JSON or missing fields. Restore a valid marker or reinstall.

Windows – EnvWriter handles Windows newlines and path values; paths with backslashes are quoted automatically.


Testing

composer test

The suite uses PHPUnit and Orchestra Testbench. It covers the installation manager, middleware, environment writing, progress, every installer route, the SQLite database flow, administrator creation, custom steps, finalization and reinstallation blocking.


Packaging this installer with an application

The installer is general purpose and does not need to know how an application is distributed. When a Laravel application ships with this package:

  • Keep application-specific logic out of the installer; register custom stages and an administrator creator in the application's service provider.
  • Set route_prefix, redirect_after_installation, administrator.model and seeders for the application.
  • Distribution archives must include this package's src/, config/, routes/ and resources/ files (or its vendor/ directory when Composer cannot be run on the target server).
  • Include a valid .env.example; the installer uses it as the base when creating .env.
  • Document that /install must be opened after deployment and that installer access should be removed afterwards.
  • Do not commit .env, installation markers or progress files to distribution archives.

For Packagist, tagging a release of this repository is enough; Composer metadata, auto-discovery, configuration publishing and view/route loading are already declared in composer.json.


License

MIT. See LICENSE.md.