Search code examples
jsonlaraveleloquentcollectionslaravel-livewire

rendering a collection throws "htmlspecialchars() expects" how can I reder it like a Eloquent collection


I call an API and put the response into a collection (thought it was a good idea) to reder it like a eloquent collection with a foreach in the blade

My trait:

class AzureRest
{
    public static function getSubscription($subscriptionId)
    {
        $token = TokenCache::getRestApiToken();
        $url = "https://management.azure.com/subscriptions/".$subscriptionId."?api-version=2020-01-01";
        $json = Http::withToken($token)->get($url);
        return collect(json_decode($json, true, 5))->all();
    }
}

my livewire controller

class ShowSubscriptions extends Component
{
    public $subscriptionId;

    public function mount()
    {
        $this->subscriptionId;
    }

    public function render()
    {
        return view('livewire.azure.show-subscriptions',
        [
            'details' => AzureRest::getSubscription($this->subscriptionId)
        ]);
    }
}

my blade

<div>
    @foreach($details as $detail)
        <p>{{$detail->foo}}</p>
        <p>{{$detail->bar}}</p>
        <p>{{$detail->baz}}</p>
    @endforeach
</div>

this is how the collection looks like:

enter image description here


Solution

  • I should better sleep more, I finally got it:

    I removed the collection on the trait

    - return collect(json_decode($json, true, 5))->all();
    
    + return json_decode($json, true, 5);
    

    and access the array as usual

            <p>{{$details['id']}}</p>
            <p>{{$details['displayName']}}</p>
            <p>{{$details['subscriptionPolicies']['spendingLimit']}}</p>
    

    Happy coding ;)