Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Laravel:Cannot access offset of type string on string

Problem:Cannot access offset of type string on string.

$array = $response->getBody()->getContents();
            $json = json_decode($array, true);
            $collection = collect($json);
            $access_token = $collection->get('access_token');
            Log::info('Got the token!');

                   return $access_token;
Enter fullscreen mode Exit fullscreen mode

Image description

Solution
It sounds like you're trying to access an offset of a string in Laravel, but the variable you're trying to access is also a string. In PHP, arrays have offsets, but strings do not. You will need to convert the string to an array first in order to access its offsets.

You can use the str_split() function to convert a string to an array, where each character in the string becomes an element in the array.

Then you can access the offset of the string by using the square brackets [] with the index of the offset you want to access.

$string = "Hello World";
$string_array = str_split($string);
echo $string_array[0];
Enter fullscreen mode Exit fullscreen mode
$array = $response->getBody()->getContents();
            $json = json_decode($array, true);
            $collection = collect($json);
            $access_token = $collection->get('access_token');
            Log::info('Got the token!');
$string_array = str_split($access_token );
                   return $string_array ;
Enter fullscreen mode Exit fullscreen mode

Remove double slash
in env
Image description

Top comments (0)