/Laravel-Multi-Tenancy-Trait

Demo-project showing multi-tenancy in Laravel with one simple trait.

Primary LanguagePHP

Laravel Multi-Tenancy Trait

This is a demo-project, partly generated with our QuickAdminPanel.com, to show you how easy it is to add multi-tenancy, so every user would see only the entries they created.

This project was created during live-coding video: view on YouTube

The whole "magic" is in this trait: app/Traits/Multitenantable.php:

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Multitenantable {

    public static function bootMultitenantable() {
        if (auth()->check()) {
            static::creating(function ($model) {
                $model->created_by_user_id = auth()->id();
            });
            static::addGlobalScope('created_by_user_id', function (Builder $builder) {
                if (auth()->check()) {
                    return $builder->where('created_by_user_id', auth()->id());
                }
            });
        }
    }

}

How to use

  • Clone the repository with git clone
  • Copy .env.example file to .env and edit database credentials there
  • Run composer install
  • Run php artisan key:generate
  • Run php artisan migrate --seed (it has some seeded data for your testing)
  • That's it: launch the main URL and login with default credentials admin@admin.com - password

License

Basically, feel free to use and re-use any way you want.


More from our LaravelDaily Team