0

In Laravel, I'm trying to create an array of some existing values I have that are built from values from a JSON object.

I have the 4 variables set and they dump properly but I'd like to add all 4 (username, perms, roles, access) to the array (IdentifierArray) with their own key/name so that when I add the array to the session and inspect it, I can see each value with it's key/name.

Code at this point:

$IdentifierArray = [];

$Username = $login->username;
$Perms = $login->permissions;
$Roles = $login->roles;
$Access = $login->access;

Session::put('Array of Values', $identifierArray);

So I'd like to add those object values to the array in the best way while having a key for each as well, like:

Array(
    "username": $username value,
    "perms":$perms value,
    "Roles":$roles value,
    "Access":$Access value
)
3
  • So, the problem is? Commented Feb 6, 2019 at 15:01
  • You don't know about $identifierArray['key'] = 'value';? Commented Feb 6, 2019 at 15:01
  • @u_mulder but I'm just wondering about adding the key to each of the 4 objects within the array Commented Feb 6, 2019 at 15:04

3 Answers 3

3

Another way of doing it, equal to @danboh:

$IdentifierArray = [
  "username" => $login->username,
  "permissions" => $login->permissions,
  "roles" => $login->roles,
  "access" => $login->access
];
Sign up to request clarification or add additional context in comments.

Comments

1

Why not use a regular PHP array? Like:

$IdentifierArray["username"] = $login->username;
$IdentifierArray["permissions"] = $login->permissions;
$IdentifierArray["roles"] = $login->roles;
$IdentifierArray["access"] = $login->access;

2 Comments

I may do this, I just wasn't sure if there was a better way I should go about it within laravel. This should still do the job though, thanks!
In that case, take a look at the toArray() method in your collection laravel.com/docs/5.7/collections#method-toarray
1

You can use the array_only helper to make your life easy:

$identifierArray = array_only(
    json_decode($login, true), 
    ['username', 'permissions', 'roles', 'access']
);

Another option would be to use the only() Collection method:

collect(json_decode($login, true))
    ->only(['username', 'permissions', 'roles', 'access'])
    ->all();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.