Laravel convert input name array to dot notation

Viewed 687

How do I convert an input name array to dot notation, similar to the way the validator handles keys? I'd like it to work for non-arrays as well.

For example, say I have:

$input_name_1 = 'city';
$input_name_2 = 'locations[address][distance]';

How would I convert that to:

$input_dot_1 = 'city';
$input_dot_2 = 'locations.address.distance';
2 Answers

If we're just talking about converting the string representation, e.g. converting strings as follows...

  • 'foo[1]' -> 'foo.1'
  • 'foo[bar]' -> 'foo.bar'
  • 'foo[bar][baz]' -> 'foo.bar.baz'

The following code does it just fine...

$string = str_replace('[', '.', $string); // Replace [ with .
$string = str_replace(']', '', $string); // Remove ]

NOTE: I could not find anyway to achieve this within the Laravel framework using existing Laravel classes/methods - but would love to know if there is a way.

Here is a hint, you could remove ] and then replace [ with a dot:

psuedocode:

$input_name_2 = 'locations[address][distance]';
$halfway = removeClosingBracket($input_name_2); // locations[address[distance
$result = replaceOpeningBracektWithDot($halfway); // locations.address.distance
Related