2

How to access key/value of the array in Laravel 4 ?

CREATE

echo Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S');

SHOW

{{{ $shirt->size or ''}}}

RESULT

It keep showing me L, but I want to Display as Large

Can anybody tell me how to do that, please ?

1
  • $shirt->size['L'] ? Commented Nov 18, 2014 at 14:04

2 Answers 2

1

The short answer is you can't, or at least not in the way you're expecting. When an item is selected and posted back to you, all that is sent back is the value of the <option> element, not it's content.

Note that:

{{ Form::select('size', array('L' => 'Large', 'S' => 'Small'), 'S') }}

produces HTML a little like this:

<select name="size">
    <option value="L">Large</option>
    <option selected value="S">Small</option>
</select>

But the key-value pairing between "L" and "Large" etc. is now lost. It's used to create the HTML markup, but nothing more - it's not stored anywhere for you to access it directly through Laravel.

When your form is submitted and posted to wherever it's meant to be posted, your browser only sends the value, in this case "L". Laravel has no idea that "L" means "Large". You will need to have this information stored elsewhere, for example:

$sizes = array(
    'L' => 'Large',
    'S' => 'Small'
);

Then you could use (provided $sizes is passed to your View):

{{ Form::select('size', $sizes, 'S') }}

and retrive the value with $sizes[$shirt->size].

If you want to be extra careful (as someone could edit the HTML to submit a value different from "L" or "S"), you can do something like

$size = (array_key_exists($shirt->size, $sizes) ? $sizes[$shirt->size] : '');

A second idea, as it looks like you have a Shirt model, would be to add the following to that class:

public $sizes = array('L' => 'Large', 'S' => 'Small');

public function getSizeAttribute($v) {
    return (array_key_exists($v, $this->sizes) ? $this->sizes[$v] : '');
}

Then $shirt->size will do exactly what you want and spit out "Large".

Sign up to request clarification or add additional context in comments.

Comments

1
{{ Form::select('size', array('Large' => 'Large', 'Small' => 'Small'), 'Small') }}

While waiting for someone to help me with this question. I did the above code and it seem to do the trick as what I wanted.

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.