# Troubleshooting: Tenant Database Connection Issues

## Issue
When performing actions like **Edit**, **Update**, or **Delete** on Tenant resources (e.g., Products), you might encounter the following error:

```
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
```

## Cause
This error occurs because of the execution order of Laravel's middleware and Route Model Binding.

1.  **Route Model Binding (Implicit):** Laravel attempts to resolve dependencies like `public function edit(Product $product)` *before* the controller method is executed. This happens in the `SubstituteBindings` middleware.
2.  **Tenant Context Setup:** Our `SetupTenantContext` middleware, which switches the database connection to the specific tenant's database, might be running *after* or in parallel with the binding resolution, or the binding resolution defaults to the 'default' connection configuration which is empty or invalid for tenants until explicitly set.

Since the `Product` model is configured to use the `tenant` connection (`protected $connection = 'tenant';`), and the `tenant` connection configuration is empty or invalid until `SetupTenantContext` runs, the query fails with "No database selected".

## Solution
To resolve this, we bypass implicit Route Model Binding for tenant-specific routes and use **explicit lookup** within the controller methods.

By accepting the `$id` instead of the model instance, we ensure that the database query (`Product::findOrFail($id)`) runs *inside* the controller method. At this point, the `SetupTenantContext` middleware has definitely finished executing and the correct tenant database connection is active.

### Code Example (ProductController)

**Before (Fails):**
```php
public function destroy(Product $product)
{
    // Implicit binding triggers query before middleware setup is complete
    $product->delete();
}
```

**After (Works):**
```php
public function destroy($id)
{
    // Query runs inside method, after tenant DB is connected
    $product = Product::findOrFail($id);
    $product->delete();
}
```

## Affected Methods
We have applied this fix to:
- `edit($id)`
- `update(Request $request, $id)`
- `destroy($id)`

## Future Improvements
A long-term architectural fix would involve reordering the middleware stack to ensure `SetupTenantContext` always runs before `SubstituteBindings` globally or within the specific route group. However, the explicit lookup method is robust and guarantees correct execution context.
