PHP code example of somnambulist / laravel-doctrine-tenancy

1. Go to this page and download the library: Download somnambulist/laravel-doctrine-tenancy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

somnambulist / laravel-doctrine-tenancy example snippets



namespace App\Entity;

use Somnambulist\Tenancy\Contracts\BelongsToTenant as BelongsToTenantContract;
use Somnambulist\Tenancy\Contracts\BelongsToTenantParticipant;
use Somnambulist\Tenancy\Contracts\TenantParticipant;
use Somnambulist\Tenancy\Entities\Concerns\BelongsToTenant;

class User implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract, BelongsToTenantContract, BelongsToTenantParticipant
{
    use BelongsToTenant;

    protected $tenant;

    public function __construct(TenantParticipant $tenant)
    {
        $this->tenant = $tenant;
    }

    public function getTenantParticipant()
    {
        return $this->tenant;
    }
}


namespace App\Entity;

use Somnambulist\Tenancy\Contracts\TenantParticipant as TenantParticipantContract;
use Somnambulist\Tenancy\Entities\Concerns\TenantParticipant;

class Account implements TenantParticipantContract
{
    
    use TenantParticipant;
}


// tenant selection and error routes
Route::group(['prefix' => 'tenant', 'as' => 'tenant.', 'middleware' => ['auth']], function () {
    Route::get('select',          ['as' => 'select_tenant',             'uses' => 'TenantController@selectTenantAction']);
    Route::get('no-tenants',      ['as' => 'no_tenants',                'uses' => 'TenantController@noTenantsAvailableAction']);
    Route::get('no-access',       ['as' => 'access_denied',             'uses' => 'TenantController@accessDeniedAction']);
    Route::get('not-supported',   ['as' => 'tenant_type_not_supported', 'uses' => 'TenantController@tenantTypeNotSupportedAction']);
    Route::get('invalid-request', ['as' => 'invalid_tenant_hierarchy',  'uses' => 'TenantController@invalidHierarchyAction']);
});


// Tenant Aware Routes
Route::group(['prefix' => 'account/{tenant_creator_id}', 'as' => 'tenant.', 'namespace' => 'Tenant', 'middleware' => ['auth', 'auth.tenant']], function () {
    Route::get('/', ['as' => 'index', 'uses' => 'DashboardController@indexAction']);

    // routes that should be limited to certain ParticipantTypes
    Route::group(['prefix' => 'customer', 'as' => 'customer.', 'namespace' => 'Customer', 'middleware' => ['auth.tenant.type:crm']], function () {
        Route::get('/', ['as' => 'index', 'uses' => 'CustomerController@indexAction']);
    });
});



class AuthController extends Controller
{
    /**
     * @param Request $request
     * @param User    $user
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function authenticated($request, $user)
    {
        // do post authentication stuff...
        //$user->setLastLogin(Carbon::now());
        //$em = app('em');
        //$em->flush($user);

        // redirect to tenant uri
        return app('auth.tenant.redirector')->resolve($user);
    }
}



class AuthController ...
{
    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request,
                $validator
            );
        }

        $user = $this->create($request->all());
        Auth::login($user);

        // call into redirector which was previously mapped above
        return $this->authenticated($request, $user);
    }
}


namespace App\Entity;

use Somnambulist\Tenancy\Contracts\TenantAware as TenantAwareContract;
use Somnambulist\Tenancy\Entities\Concerns\TenantAware;

class Customer implements TenantAwareContract
{
    use TenantAware;
}


namespace App\Repository;

use Somnambulist\Tenancy\Repositories\TenantAwareRepository;

class AppTenantAwareRepository extends TenantAwareRepository
{

}


namespace App\Repository\TenantAware;

use App\Repository\AppTenantAwareRepository;

class CustomerRepository extends AppTenantAwareRepository
{

}

    [
        'repository' => \App\Repository\TenantAware\CustomerRepository::class,
        'base'       => \App\Repository\CustomerRepository::class,
        //'alias'      => 'app.repository.tenant_aware_customer', // optionally alias
        //'tags'       => ['repository', 'tenant_aware'], // optionally tag
    ],


class AppTenantAwareRepository extends TenantAwareRepository
{

    protected function applyGlobalSecurityModel(QueryBuilder $qb, $alias)
    {
        $qb
            ->where("({$alias}.tenantOwnerId IS NULL OR {$alias}.tenantOwnerId = :tenantOwnerId)")
            ->setParameters([
                ':tenantOwnerId' => $this->tenant->getTenantOwnerId(),
            ])
        ;
    }
}


class Kernel extends HttpKernel
{
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

        // must appear AFTER maintenance mode, but before everything else
        \Somnambulist\Tenancy\Http\Middleware\TenantSiteResolver::class,
        \Somnambulist\Tenancy\Http\Middleware\TenantRouteResolver::class,

        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.tenant' => \Somnambulist\Tenancy\Http\Middleware\AuthenticateTenant::class,
        'auth.tenant.type' => \Somnambulist\Tenancy\Http\Middleware\EnsureTenantType::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    ];
}


// config/app.php
return [
    // other stuff...
    'multi_site' => [
        'router' => [
            'namespace' => 'App\Http\Controller', // default
        ],
    ],
    // more stuff...
];


// config/app.php
return [
    // other stuff...
    'multi_site' => [
        'router' => [
            'namespace' => 'App\Http\Controller', // default
            'patterns' => [
                'id' => '[0-9]+',
            ],
        ],
    ],
    // more stuff...
];