Have you tried composer dump-autoload?
Dec 15, 2020
24
Level 4
error : trait is not found (using in models)
Hi, I have some trait that I want to use it in my models.
here I have two traits that I want to use :

the error is: a trait is not found.

<?php
namespace App\Models;
use App\Models\Services\Permissions\Traits\HasPermissions;
use App\Models\Services\Roles\Traits\HasRoles;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable , HasRoles , HasPermissions;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
<?php
namespace App\Models\Services\Permissions\Traits;
use App\Models\Permission;
use Illuminate\Support\Arr;
trait HasPermissions
{
/* ===== permissions ===== */
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
protected
function getAllPermissions(array $permissions)
{
return Permission::whereIn('name', Arr::flatten($permissions))->get();
}
public function givePermissions(... $permissions)
{
$permissions = $this->getAllParmissions($permissions);
if ($permissions->isEmpty()) return $this;
$this->permissions()->syncWithoutDetaching($permissions);
return $this;
}
public function withdrawPermissions(... $permissions)
{
$permissions = $this->getAllParmissions($permissions);
$this->permissions()->detach($permissions);
return $this;
}
public function refreshPermissions(... $permissions)
{
$permissions = $this->getAllParmissions(Arr::flatten($permissions));
$this->permissions()->sync($permissions);
return $this;
}
public function hasPermission(Permission $permissions)
{
return $this->permissions->contains($permissions);
}
}
<?php
namespace App\Models\Services\Roles\Traits;
use App\Models\Role;
use Illuminate\Support\Arr;
trait HasRoles
{
/* ==== roles ==== */
public function roles()
{
return $this->belongsToMany(Role::class);
}
protected function getAllRoles(array $roles)
{
return Role::whereIn('name', Arr::flatten($roles))->get();
}
public function giveRoles(... $roles)
{
$roles = $this->getAllRoles($roles);
if ($roles->isEmpty()) return $this;
$this->Roles()->syncWithoutDetaching($roles);
return $this;
}
public function withdrawRoles(... $roles)
{
$roles = $this->getAllRoles($roles);
$this->roles()->detach($roles);
return $this;
}
public function refreshRoles(... $roles)
{
$roles = $this->getAllRoles($roles);
$this->roles()->sync($roles);
return $this;
}
public function hasRole(string $role)
{
return $this->roles->contains('name', $role);
}
}
Please or to participate in this conversation.