The-WebGuy
The-WebGuy

Reputation: 937

Laravel Blade - retrieve element by id

I would like to retrieve an element by the id.

inside my blade file:

{{ $auctionStatuses }}

This outputs:

[
    {
        "id":1,
        "name":"Awaiting customer action",
        "created_at":"2018-10-04 10:14:08",
        "updated_at":"2018-10-04 10:14:08"
    },
    {
        "id":2,
        "name":"Transfer in progress",
        "created_at":"2018-10-04 10:15:11",
        "updated_at":"2018-10-04 10:15:11"
    },
    {
        "id":3,
        "name":"Completed",
        "created_at":"2018-10-04 10:15:14",
        "updated_at":"2018-10-04 10:15:14"
    }
] 

I would like to output the name when referencing by the id field

Due to some data coming from mongodb, i can't use the standard relationships

I have tried this {{ $auctionStatuses['3'] }} but that doesn't exist, obviously.

i guess ideally, i would like to do something like this

{{ $auctionStatuses[*]->id['3']->name }}

Is there a way to do what i need, without looping through the json array?

Upvotes: 2

Views: 3260

Answers (2)

Farouk M
Farouk M

Reputation: 1295

You can use :

$auctionStatuses->firstWhere('id',3)->name;

https://laravel.com/docs/5.7/collections#method-first-where

Upvotes: 3

With one line:-

$auctionStatuses->toArray()[array_search(3,array_column($auctionStatuses->toArray(),'id'))]['name']

Explanation

toArray() Method converting a laravel collection to an array.

array_search Will searching for a array element and returning the index

array_column will returning values with specify column

Upvotes: 5

Related Questions