Mntfr Mntfr - 27 days ago 11
PHP Question

Cant access an object property in laravel

I am getting results from a database in a controller and storing them as objects in an array

$roleSentinel = Sentinel::findRoleByName($role);
$permisssionsName = array_keys($roleSentinel['permissions']);
$permissions = array();

foreach ($permisssionsName as $permiso) {
$permissions[] = DB::table('sec_permission')->where('name', '=',$permiso)->get();
}

return view('menu', ['role' => $role,'permisos' => $permisos]);


an object would be like

[{"permission_id":1,"name":"foo","object_id":1,"operation_id":1}]


So then in the view I am trying to get the values and printing them

<b>{{$role}}</b><br>
@foreach ($permisos as $permiso)
@foreach ($permiso->name as $name)
{{$name}}
@endforeach
@endforeach


however I am getting
Undefined property: Illuminate\Support\Collection::$name

Answer

Each variable in the array is an array of objects. There's two ways you can go about it.

Add another foreach:

@foreach ($permisos as $permiso)

    @foreach ($permiso as $perm)
        @foreach ($perm->name as $name)
           {{$name}}
        @endforeach
    @endforeach
@endforeach

Or get one full collection with all of the names:

$permissionsName = array_keys($roleSentinel['permissions']);

$permissions = DB::table('sec_permission')->whereIn('name',$permissionsName)->get();