SerhiiNuzhnyi's avatar

Cannot use object of type stdClass as array

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]);;        
    }
0 likes
11 replies
Snapey's avatar
Snapey
Best Answer
Level 122

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's avatar

@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's avatar

@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's avatar

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 :).

2 likes
Jazekss's avatar

Same problem, error: Cannot use object of type stdClass as array I am fetching data from database by controller and operate data in model, i get first error:

public function index():View {
        $toolsQuery = DB::select('SELECT * FROM rent ORDER BY id ASC');
        $tools = [];
        foreach ($toolsQuery as $tool) {
            $tools[] = new Tools(
                (int)$tool['id'],
                (string)$tool['category'],
                (string)$tool['model'],
                (string)$tool['title'],
                (string)$tool['description'],
                (int)$tool['price_day'],
                (int)$tool['price_week'],
                (string)$tool['image'],
            );
            dump($tools);
        }
        return view('rent.index')->with($toolsQuery);
    }

And when chage from DB::select to DB::selectResultSets i get this: Undefined array key "id"

I am only starting Laravel and i am not so good at PHP, but i am trying and want to learn more, cant finish project, before i create this project my my self (only routing sistem was integrated), now need to renew and make some changes, and i can, someone can help me? I ma googling 3 days and nothing

Snapey's avatar

You should start your own question, not drag out an unrelated question from 7 years ago.

You need to add get() to execute the query in order to fetch the array of data

DB::select('SELECT * FROM rent ORDER BY id ASC')->get();

But you should work to learn more about Laravel and eloquent because your code could be vastly improved.

tykus's avatar

@Snapey not required to add get in this case; DB::select is enough to execute a query.

You need to add get() to execute the query in order to fetch the array of data

@jazekss you are getting stdClass instances, so use the Object Operator -> rather than Array Access:

$tool->id
// instead of...
$tool['id']
// etc
Jazekss's avatar

@Snapey Sorry, next time i will start own question and add ->get() wont help for me

Jazekss's avatar

@tykus tryed this, i get this error: Attempt to read property "id" on array

Now my code looks like this:

(int)$tool->id,

And i use:

$toolsQuery = DB::selectResultSets('SELECT * FROM rent ORDER BY id ASC');

and get error: I get this Attempt to read property "id" on array

And if i use

$toolsQuery = DB::select('SELECT * FROM rent ORDER BY id ASC'); 

i get this:

Too few arguments to function App\Models\Tools::__construct(), 0 passed in C:.Additional\XAMPP_8.2.12_PHP.8.2.12\htdocs\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasEvents.php on line 67 and exactly 9 expected

Even ->get() wont help

And if i try to dump() after fetch data from db its give all database content what i ask

tykus's avatar

@Jazekss start you own question... this is getting in the weeds on a zombie thread.

Please or to participate in this conversation.