0

this is modified seeder code

$user = User::where('id', 1)->get();
        $role = Role::where('id', 1)->get();
        echo $role;
        $user->assignRole([$role->id]);

this is the output

[{"id":1,"team_id":2,"name":"Admin","guard_name":"web","created_at":"2023-01-10T06:40:56.000000Z","updated_at":"2023-01-10T06:40:56.000000Z"}]
   Exception 

  Property [id] does not exist on this collection instance.

  at vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php:969
    965▕      */
    966▕     public function __get($key)
    967▕     {
    968▕         if (! in_array($key, static::$proxies)) {
  ➜ 969▕             throw new Exception("Property [{$key}] does not exist on this collection instance.");
    970▕         }
    971▕ 
    972▕         return new HigherOrderCollectionProxy($this, $key);
    973▕     }

  1   database/seeders/CreateAdminUserSeeder.php:32
      Illuminate\Support\Collection::__get("id")

      +22 vendor frames 
  24  artisan:37
      Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

you can see that the id is there on echo but I cant assign the role using its id

this only happed when teams set to trues in config file.

I am missing something or is it a bug?(highly doubt it )

apokryfos
  • 38,771
  • 9
  • 70
  • 114
drphp
  • 1
  • 3

1 Answers1

1

$role = Role::where('id', 1)->get(); returns a collection of roles

Instead you can either do:

$role = Role::find(1);

or

$role = Role::where('id', 1)->first();

To clear the cache when adding new permissions/roles run the following artisan commands:

php artisan cache:clear

For reference you can run the following to clear everything cached:

php artisan cache:clear
php artisan view:clear
php artisan config:clear
php artisan route:clear
RG Servers
  • 1,726
  • 2
  • 11
  • 27
  • thanks for answering but it did not work ``` {"id":1,"team_id":2,"name":"Admin","guard_name":"web","created_at":"2023-01-10T06:40:56.000000Z","updated_at":"2023-01-10T06:40:56.000000Z"} Spatie\Permission\Exceptions\RoleDoesNotExist There is no role with id `1`. at vendor/spatie/laravel-permission/src/Exceptions/RoleDoesNotExist.php:16 12▕ } 13▕ 14▕ public static function withId(int $roleId) 15▕ { ➜ 16▕ return new static("There is no role with id `{$roleId}`."); 17▕ } 18▕ } 19▕ ``` – drphp Jan 10 '23 at 15:48
  • You need to clear your config/cache when creating a new role/permission, check my modified answer, and it works for you, kindly mark it as complete (check mark) – RG Servers Jan 11 '23 at 04:00