Search code examples
arrayslaravelcollectionseloquentlaravel-query-builder

Can't pass element from array to view


Trying to -unsuccessfully- pass as separated values into view from this array:

  #items: array:1 [▼
    0 => {#548 ▼
      +"location": "Guadalajara"
      +"location_id": 34
    }
  ]
}

This array comes after a leftjoin query

$default_loc = DB::table('users')
                ->leftJoin('locations', 'users.location_id','=','locations.id')
                ->where('users.id',auth()->user()->id)
                ->select('location', 'location_id')
                ->get();

If I try to pass this array to the view via compact('default_loc') I'd been only able to show the entire array as shown above with {{ $default_loc }}, but can't separate it into $default_loc->location and $default_loc->id.

Thank you all,


Solution

  • Since $default_loc is an array, you should treat it as an array, so to access it you need to use the [] operator:

    {{ $default_loc[0]->location_id }}
    

    However, if you are sure that only 1 record will be returned, you can use the first() method instead of get() that will give you directly the object:

    $default_loc = DB::table('users')
                ->leftJoin('locations', 'users.location_id','=','locations.id')
                ->where('users.id',auth()->user()->id)
                ->select('location', 'location_id')
                ->first();
    
    ...
    {{ $default_loc->location_id }}