Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pluck id (integer) cast to string Laravel

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]) !!}
like image 895
Sagar Chamling Avatar asked Jun 28 '17 10:06

Sagar Chamling


2 Answers

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' 
  ];
like image 80
Dharmesh Rakholia Avatar answered Sep 16 '22 12:09

Dharmesh Rakholia


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

like image 25
Sagar Chamling Avatar answered Sep 19 '22 12:09

Sagar Chamling