![]() ![]() ![]() 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. $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() 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." $permissionIDs = $role->permissions->modelKeys() $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. data->save () data->id Can be used like this. I read Laravel source code (with no objective) then found it. 555 After save, data->id should be the last id inserted. ![]() This feature started to be documented since Larave 5.2, but I found that we can use it even in Laravel 5.1. The Laravel find() method can return single or. Typical code to do this will be with pluck() function: // returns array of IDs When you want to get multiple results of find with array of ID, you can pass the array to Model::find. The Laravel find method is a useful way of retrieving records from the database using the primary key. And then you need to get IDs of permission by a certain role. While working on your Laravel application, you often need to get the recently added model ID to assign it to some other model or processing data. Imagine, that you have hasMany() relationship - one Role has many Permissions. Using getPDO () Method In this post, I want to share a quick tip about how to get the last inserted ID in Laravel. 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. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |