Cannot use object of type stdClass as array

Published 6 months ago by SerhiiNuzhnyi

I have a function in my controller. Here are three ways to get all data from database table. All work fine but I can pass to View only first. Other two which are commented cause error Cannot use object of type stdClass as array (View: /var/www/doctor_lar/resources/views/admin/role.blade.php)

public function roles_list(){
        $roles = Role::all();
        //$roles = DB::select('SELECT * FROM roles');
        //$roles = DB::table('roles')->get();
        return view('admin.role')->with(['roles'=>$roles]);;        
    }
Best Answer (As Selected By SerhiiNuzhnyi)
Snapey

the answer depends on which Laravel version you are using

The difference is the return type of eloquent and DB are not the same

In your view, are you accessing the roles like $role['name']?

MaverickChan
return view('admin.role', array ( 'roles' => $roles ));
Snapey
Snapey
6 months ago (682,495 XP)

the answer depends on which Laravel version you are using

The difference is the return type of eloquent and DB are not the same

In your view, are you accessing the roles like $role['name']?

SerhiiNuzhnyi

@MaverickChan: your code cause the same error.

@Snapey: Laravel Framework 5.4.21. I use it in blade as

<?php foreach ($roles as $role):?>
              <li>
                  <?php echo $role['name']; ?><br>
              
              </li>
                          <?php endforeach; ?>
SerhiiNuzhnyi

@Snapey thank you. I guessed what you mean. It works in next way. Cause it is array of objects not arrays.

<?php foreach ($roles as $role):?>
              <li>
                  <?php echo $role->name; ?><br>
              
              </li>
                          <?php endforeach; ?>
tim_jespers

In Laravel 5.4.21 DB:: query's will return stdObject class objects, not Eloquent models. So in blade $role['name'] should be $role->name as you cannot treat an stdObject as an array (the error is pretty explanatory in this case ;) ) the reason why the first one IS in fact working is only due to the fact that Eloquent models implement ArrayAccess by default which allows you to treat them as if they were a plain array instead of an class object. If they didn't you would get the exact same error on the first query method.

So either: go with the model approach and use array notation in views or go for stdObjects and acces their properties as stated above :).

Please sign in or create an account to participate in this conversation.