you assign role to user (as per the spatie docs. The company does not have anything to do with it.
How to create user roles based on companies using Laravel Spatie
I am using Laravel-Spatie Permission and Laravel-8 for User Role-Based Access Level:
I have these tables:
User Model:
<?php
namespace App;
use App\Model;
use Carbon\Carbon;
use Hash;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
use SoftDeletes;
protected $fillable = [
'first_name',
'other_name',
'last_name',
'company_id',
'updated_at',
'created_at',
];
public function company()
{
return $this->belongsTo('App\Models\Organization\Company');
}
}
Company Model:
<?php
namespace App\Models\Organization;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Company extends Model
{
public $timestamps = false;
protected $table = 'companies';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'company_name',
'address1',
'address2',
'org_head',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
public function users()
{
return $this->hasMany('App\User');
}
}
Each user is attached at least to a company. Apart from the SuperAdmin Role, I want Roles to belong to companies. That is, each company should create it's own Roles.
How do I achieve this?
ok, now we are getting to the actual question.
its explained here.
You could use a migration as normal to add a company_id column to the roles table, and create a global scope that limits the roles returned to only those roles of the logged in user's company (suggest storing their company in session)
Then a model observer to apply company_id whenever a model is being created.
Please or to participate in this conversation.