Home > Software design >  Get array of values from a model Laravel
Get array of values from a model Laravel

Time:12-13

Im trying to get an array of all api_token (which is a variable of my model User), but doing User:all() slows the request too much.

Is there any way of getting an array of a certain value from a model in Laravel?

My code:

$allUsers = User::all();
$allTokens = [];
foreach ($allUsers as $key => $userForeach) {
   if($userForeach->api_token){
       array_push($allTokens, $userForeach->api_token);
   }
}

CodePudding user response:

You can select only that column:

$tokens = User::select('api_token')->get()->toArray();

or

$tokens = User::all('api_tokens')->toArray();

or

$tokens = User::pluck('api_token')->toArray();

It will speed up your query because you are selecting only one column.

Also, here you can read answer.

CodePudding user response:

Put this function on your User Model

// get only API token for all users
 
  function getTokens()
{
    return  User::pluck('api_token')->toArray();   
}

then you can call it anytime from User Model

User::getTokens();

CodePudding user response:

$allUsers = User::whereNotNull('api_token')->pluck('api_token')->toArray();
$allTokens = [];
foreach ($allUsers as $userForeach) {
   $allTokens [] = $userForeach;
}

CodePudding user response:

Always try to deal with such requests immediately in the database. Your way for this case is very resource intensive. You fetch all users. Then you interact the database result with PHP.

Therefore always: SELECT 'column_name' FROM table_name; **and never SELECT * FROM table_name;

In Laravel context:

$userTokens = User::select('api_token')->get()->toArray();

CodePudding user response:

$api_token= User::whereNotNull('api_token')->pluck('api_token')->toArray(); this Code return you list of api token.

  • Related