Using Laravel Octane | laravel-multitenancy | Spatie       

 SPATIE  

  Laravel Multitenancy 
=======================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-multitenancy](https://spatie.be/docs/laravel-multitenancy/v4)  Advanced-usage  Using Laravel Octane

 Version   v4   v3   v2   v1      

 Other versions for crawler [v4](https://spatie.be/docs/laravel-multitenancy/v4) [v3](https://spatie.be/docs/laravel-multitenancy/v3) [v2](https://spatie.be/docs/laravel-multitenancy/v2) [v1](https://spatie.be/docs/laravel-multitenancy/v1) 

  Using Laravel Octane    
- [ Introduction ](https://spatie.be/docs/laravel-multitenancy/v4/introduction)
- [ Upgrade guide ](https://spatie.be/docs/laravel-multitenancy/v4/upgrade-guide)
- [ Support us ](https://spatie.be/docs/laravel-multitenancy/v4/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-multitenancy/v4/requirements)
- [ Questions and issues ](https://spatie.be/docs/laravel-multitenancy/v4/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-multitenancy/v4/changelog)
- [ ](https://spatie.be/docs/laravel-multitenancy/v4/installation-setup)

Installation
------------

- [ Base installation ](https://spatie.be/docs/laravel-multitenancy/v4/installation/base-installation)
- [ Using a single database ](https://spatie.be/docs/laravel-multitenancy/v4/installation/using-a-single-database)
- [ Using multiple databases ](https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases)
- [ Determining the current tenant ](https://spatie.be/docs/laravel-multitenancy/v4/installation/determining-current-tenant)

Basic usage
-----------

- [ Automatically determining the current tenant ](https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/automatically-determining-the-current-tenant)
- [ Working with the current tenant ](https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant)
- [ Making queues tenant aware ](https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/making-queues-tenant-aware)

Advanced usage
--------------

- [ Ensuring a current tenant has been set ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/ensuring-a-current-tenant-has-been-set)
- [ Looping over a collection of tenants ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/looping-over-a-collection-of-tenants)
- [ Making Artisan command tenant aware ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/making-artisan-commands-tenant-aware)
- [ Using a custom tenant model ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-a-custom-tenant-model)
- [ Listening for events ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events)
- [ Using tenant specific facades ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-tenant-specific-facades)
- [ Executing code for tenants and landlords ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords)
- [ Using Laravel Octane ](https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-laravel-octane)

Using tasks to prepare the environment
--------------------------------------

- [ Overview ](https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/overview)
- [ Creating your own task ](https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task)
- [ Switching databases ](https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-databases)
- [ Switching route cache paths ](https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths)
- [ Prefixing cache ](https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/prefixing-cache)

 Using Laravel Octane
====================

###  On this page 

1. [ The lifecycle of a request ](#content-the-lifecycle-of-a-request)
2. [ What a worker shares between requests ](#content-what-a-worker-shares-between-requests)
3. [ Writing your own tasks ](#content-writing-your-own-tasks)
4. [ Queues ](#content-queues)
5. [ Concurrent tasks and ticks ](#content-concurrent-tasks-and-ticks)

[Laravel Octane](https://laravel.com/docs/octane) keeps your application in memory and serves many requests from the same worker. The package detects Octane through the `LARAVEL_OCTANE` environment variable that Octane sets for its workers, and adapts its behaviour. There is nothing to configure.

The lifecycle of a request
--------------------------------------------------------------------------------------------------------------------------------------

In a PHP-FPM application the current tenant is determined when the application boots, and the whole environment is thrown away when the request ends. Inside an Octane worker the application boots once, so the package hooks into the events Octane dispatches for every request instead:

- when Octane dispatches `RequestReceived`, the package determines the current tenant with the configured tenant finder and makes it current;
- when Octane dispatches `RequestTerminated`, the package forgets the current tenant, so the switch tenant tasks restore the landlord environment before the worker picks up its next request;
- when Octane dispatches `WorkerErrorOccurred`, because the request failed before it could terminate, for instance when the client disconnected while the response was being sent, the package forgets the current tenant as well.

If a switch tenant task throws an exception while a tenant is being made current, the task that threw and the tasks before it are asked to forget the tenant again before the exception is rethrown. Cleanup is best effort: a custom task whose `forgetCurrent` also fails can still leave side effects behind. When a task throws while the tenant is being forgotten, the remaining tasks still forget it, the current tenant binding and context are cleared, and the exception is rethrown afterwards.

What a worker shares between requests
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

Octane gives every request its own copy of the service container and discards it when the request ends. Some objects are shared by all the requests a worker handles anyway: the router, the database manager and the environment repository among them. This is why the switch tenant tasks matter more with Octane than with PHP-FPM: `forgetCurrent` is the only thing that restores the landlord environment.

The tasks that ship with the package take care of this:

- [`SwitchTenantDatabaseTask`](/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-databases/) purges the tenant connection and refreshes the connection resolver of Eloquent on every switch;
- [`PrefixCacheTask`](/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/prefixing-cache/) rebuilds the cache store on every switch, so the prefix of the previous tenant is never reused;
- [`SwitchRouteCacheTask`](/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths/) loads the route cache of the tenant into the shared router, and loads the route cache of the landlord again when the tenant is forgotten. When the landlord routes are not cached, a copy of the routes the router held when the tasks were instantiated is put back instead, whatever the order of the tasks.

The `octane` cache driver is the exception: Octane creates its store once when the worker boots and that store ignores the cache prefix, so `PrefixCacheTask` cannot separate tenants there. Keep tenant data in another store, like Redis.

Do not set `APP_ROUTES_CACHE` in the worker's real environment when using `SwitchRouteCacheTask`. Laravel's immutable environment repository cannot override that value for each tenant. Request handlers that interleave tenant switches in the same process, such as concurrent coroutines or fibers, are not supported.

Writing your own tasks
--------------------------------------------------------------------------------------------------------------------------

When [creating your own task](/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task/), make sure `forgetCurrent` undoes everything `makeCurrent` changed. In a long running process nothing else restores the environment for the landlord. A task that registers routes must remove them in `forgetCurrent`, unless `SwitchRouteCacheTask` is configured too: that task puts the landlord routes back, and the routes other tasks registered go with the tenant.

Inside an Octane worker the tasks are instantiated the first time a tenant is made current in a request, and reused until that request ends. Storing the original values as properties, like the tasks of the package do, keeps working.

Queues
--------------------------------------------------------------------------

Octane only serves HTTP requests. Jobs are still processed by regular queue workers, where the package [makes the queue tenant aware](/docs/laravel-multitenancy/v4/basic-usage/making-queues-tenant-aware/) in the same way as without Octane.

Concurrent tasks and ticks
--------------------------------------------------------------------------------------------------------------------------------------

The package determines the current tenant for HTTP requests only. The closures passed to `Octane::concurrently()` and the callbacks of `Octane::tick()` run without a current tenant, also when Octane runs them in a separate worker, as Swoole does. Make the tenant current inside the closure, for instance with `$tenant->execute()`. The switch tenant tasks run there like they do in a request, and the package forgets the current tenant when the task or the tick terminates.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
