> For the complete documentation index, see [llms.txt](https://senselab.gitbook.io/senselab-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://senselab.gitbook.io/senselab-docs/vendor/spatie/laravel-multitenancy/docs/advanced-usage/ensuring-a-current-tenant-has-been-set.md).

# Ensuring a current tenant has been set

In your project you probably will have many routes where you expect a tenant has been made current.

You can ensure that a current tenant has been set by applying the `\Spatie\Multitenancy\Http\Middleware\NeedsTenant` middleware on those routes.

We recommend registering this middleware in a group alongside `\Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession`, to also verify that the session is not being abused across multiple tenants.

```php
// in `app\Http\Kernel.php`

protected $middlewareGroups = [
    // ...
    'tenant' => [
        \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class,
        \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class
    ]
];
```

With the middleware registered, you can use it in routes files (or in a route service provider).

```php
// in a routes file

Route::middleware('tenant')->group(function() {
    // routes
})
```

If the request does not have a "current" tenant for these routes, an `Spatie\Multitenancy\Exceptions\NoCurrentTenant` exception will be thrown. You can listen for that exception in [the exception handler](https://laravel.com/docs/master/errors#the-exception-handler). You could set some kind of flash message and redirect to a login page there.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://senselab.gitbook.io/senselab-docs/vendor/spatie/laravel-multitenancy/docs/advanced-usage/ensuring-a-current-tenant-has-been-set.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
