How to Get Array of Ids from Eloquent Models in Laravel?
Hello Friends,
In this post, we will learn laravel get array of ids from eloquent models. let’s discuss about laravel get array of ids from eloquent models. This article will give you a simple example of laravel get array of ids from eloquent models. This article goes in detailed on laravel get array of ids from eloquent models.
Sometimes we need to get an array of ids from the table. There are two ways to get an array of ids in laravel. Laravel provides pluck() and modelKeys() eloquent methods to get an array from the collection in laravel. so let's see both example below:
You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.
Example 1: using pluck() app/Http/Controllers/DemoController.php<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class DemoController extends Controller { /** * Write code on Method * * @return response() */ public function index(Request $request) { $usersIDs = User::pluck('id')->toArray(); dd($usersIDs); } }Output:
Array ( [0] => 1 [1] => 2 [2] => 11 [3] => 12 [4] => 13 [5] => 14 [6] => 15 [7] => 16 [8] => 17 [9] => 18 )Example 2: using modelKeys() app/Http/Controllers/DemoController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\User; class DemoController extends Controller { /** * Write code on Method * * @return response() */ public function index(Request $request) { $usersIDs = User::all()->modelKeys(); dd($usersIDs); } }Output:
Array ( [0] => 1 [1] => 2 [2] => 11 [3] => 12 [4] => 13 [5] => 14 [6] => 15 [7] => 16 [8] => 17 [9] => 18 )
I hope it can help you...
Divyang Vadodariya
My name is Divyang Vadodariya. I'm a full-stack developer, entrepreneur and owner of RvSolutionStuff. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap ,etc from the early stage.

We are Recommending you
- How To Find Length Of A String In Python?
- How To Calculate Age From Date Of Birth In PHP?
- Laravel 9 One To One Relationship Tutorial With Example
- Laravel 9 Store Log Of Eloquent SQL Queries
- Laravel One to Many Eloquent Relationship Tutorial
- Search Value Using Binary Search In C Example
- Error: Class "App\Http\Controllers\Validator" not found
- Laravel Google Maps Multiple Markers Example
- How to Http Curl Delete Request in Laravel?
- How to Get Array of Ids from Eloquent Models in Laravel?
Copyright © 2023 www.RVSolutionStuff.com • All Rights Reserved