Pluck id (integer) cast to string Laravel

2020-07-06 05:36发布

While plucking from a database, I get id as strings.

$alphabets = new Alphabet();
return $alphabets->pluck('name', 'id');

Output

{
    "1": "Apple",
    "2": "Ball",
    "3": "Cat"
}

Expected

{
    1: "Apple",
    2: "Ball",
    3: "Cat"
}

But, when I reverse ID and name,

return $alphabets->pluck('id', 'name');

I get id as integer.

{
    "Apple": 1,
    "Ball": 2,
    "Cat": 3
}

I'm not sure what's happening behind the scene. But how can I get ID in integer ? Actually, old flash session doesn't set value because of 1 vs "1" in Form Collective.

{!! Form::select('alphabet', $alphabets, null, ['class' => 'form-control', 'multiple' => true]) !!}

5条回答
闹够了就滚
2楼-- · 2020-07-06 06:03

Usually, pluck() method gives you associative array of values in string values.

So, try using select statements like this:

$data = Alphabet::select('id','name')->get()->toArray();

This will give you following result:

array:3 [▼
  0 => array:2 [▼
    "id" => 1
    "name" => "Apple"
  ]
  1 => array:2 [▼
    "id" => 2
    "name" => "Ball"
  ]
  2 => array:2 [▼
    "id" => 3
    "name" => "Cat"
  ]
]

Now, using simple loop you can get your expected array.

$expected = array();

foreach($data as $d){
    $expected[$d['name']] = $d['id'];
}

dd($expected);
查看更多
做自己的国王
3楼-- · 2020-07-06 06:07

I think I found the answer here.

https://laracasts.com/discuss/channels/laravel/pluck-id-integer-cast-to-string

Here I found JSON only allows key names to be strings.

Using number as "index" (JSON)

{
    "1": "Apple",
    "2": "Ball",
    "3": "Cat"
}

Actually, I want to achieve it for Form Collective. It was a bug and it's PR has been merged now.

https://github.com/LaravelCollective/html/pull/368#pullrequestreview-46820423

查看更多
啃猪蹄的小仙女
4楼-- · 2020-07-06 06:08

Try this code

$alphabets = new Alphabet();
return $alphabets->all()->pluck('name', 'id');

Alphabet.php

You should cast your columns like this.

  protected $casts = [
    'id' => 'integer',
    'name' => 'string' 
  ];
查看更多
Summer. ? 凉城
5楼-- · 2020-07-06 06:23

you also convert key into int

 $alphabets = new Alphabet();
    $alphaArr =$alphabets->pluck('name', 'id');
    foreach($array as $key => $value) {
       $newArray[(int) $key] = $value;
    }
查看更多
倾城 Initia
6楼-- · 2020-07-06 06:27

Adding this line fix the old session issue of LaravelCollective/Html.

|| in_array((string) $value, $selected, true)

/**
 * Determine if the value is selected.
 *
 * @param  string $value
 * @param  string $selected
 *
 * @return null|string
 */
protected function getSelectedValue($value, $selected)
{
    if (is_array($selected)) {
        return in_array($value, $selected, true) || in_array((string) $value, $selected, true) ? 'selected' : null;
    } elseif ($selected instanceof Collection) {
        return $selected->contains($value) ? 'selected' : null;
    }
    return ((string) $value == (string) $selected) ? 'selected' : null;
}
查看更多
登录 后发表回答