
Get Array of IDs from Eloquent Collection
-
Get array of IDs from Eloquent relationships using pluck function
--PATH app\Http\Controllers\<YourController>.php$post = Post::where('id',1)->first(); $commentIDs = $post->comments->pluck('id'); //Data in object collection print_r($commentIDs); //Data in array print_r($commentIDs->toArray());
0Sometimes you have to get the Array of IDs from eloquent collection for some records. Imagine, that you have hasMany() relationship – one Post has many Comments. And then you want to get IDs of comments by a certain Post. You can get the IDs of comments of the related post using pluck function.
Output
Data in Collection Object
Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => 3 [1] => 4 [2] => 5 ) )
Data in Array
Array ( [0] => 3 [1] => 4 [2] => 5 )
-
Get array of IDs from Eloquent relationships using modelKeys function
--PATH app\Http\Controllers\<YourController>.php$post = Post::where('id',1)->first(); $commentIDs = $post->comments->modelKeys(); print_r($commentIDs); $comments = Comment::whereIn('id', $commentIDs)->get();
0You can use modelKeys method on eloquent relationship method comments (hasMany) to get the IDs of the comments table records which are related to this particular post. You can also get all the comments using these IDs with whereIn method in laravel. The value of $commentIDs should be in array format.
Output
Array ( [0] => 3 [1] => 4 [2] => 5 )
Random Code Snippet Queries: Laravel
- Update if exist else insert new record in laravel
- How to pass external link in laravel blade to anchor tag
- Import/Use Storage facade in laravel
- Run artisan command to generate key in laravel
- Credit card validation in laravel
- Laravel 9 pagination with search filter
- First and last item of the array using foreach iteration in laravel blade
- Display data in table using foreach in Laravel
- Laravel route parameter
- How to fetch single row data from database in laravel
- Get last record from table in laravel
- How to change default timestamp fields name in Laravel
- How to add class to tr in table using foreach in laravel
- How to call Laravel route in jQuery
- How to restore deleted records in laravel
- Get current month records in laravel 7/8
- Method Illuminate\Events\Dispatcher::fire does not exist
- Get today records in Laravel
- How to get records in random order in laravel
- Redirect from www to non www in laravel using htaccess
- Return view from route Laravel
- Shorter syntax for whereHas with call back function in laravel
- How to update record after save method in Laravel
- Get latest record by created at in Laravel
- How to insert dynamic values to additional column with pivot column in pivot table on multiple records