The workaround is to get all results into Collection and then get the keys: $allPermissions = Permission::all()->modelKeys() īut it may cause performance issues if you're getting all records for big table. If you would like to generate a database migration when you generate the model, you may use the -migration or -m option: php artisan make:model User -migration. The easiest way to create a model instance is using the make:model Artisan command: php artisan make:model User. $permissions = $role->permissions->pluck('id') īut in case of modelKeys(), this will fail with error "Call to undefined method App\Models\Permission::modelKeys()": $allPermissions = Permission::modelKeys() All Eloquent models extend Illuminate\Database\Eloquent\Model class. So method pluck() exists for both Model and Collection, so both would work: $allPermissions = Permission::pluck('id') Notice that, as I said before, it works on Collections, not on just Laravel model. Official description of modelKeys() method is pretty short: "Get the array of primary keys." You may use the make:model Artisan command to generate a new model: php artisan make:model Flight. Models typically live in the appModels directory and extend the IlluminateDatabaseEloquentModel class. $permissionIDs = $role->permissions->modelKeys() To get started, lets create an Eloquent model. $permissionIDs = $role->permissions->pluck('id') īut what if your auto-increment primary key name is not "id"? Apparently, you can get the key(s) from Laravel model, with method modelKeys() on Collection: // Same result as above. Typical code to do this will be with pluck() function: // returns array of IDs And then you need to get IDs of permission by a certain role. Imagine, that you have hasMany() relationship - one Role has many Permissions. I will show you two quick ways to do it - one is pretty popular, and another is a function which I found out only today. There are situations where you need to get array of IDs for some records in collection/table. Actually firstOrCreate would not update in case that the register already exists in the DB.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |