Home > Net >  "Cannot access offset of type string on string" while using foreach loop
"Cannot access offset of type string on string" while using foreach loop

Time:11-30

I'm receiving an error while using the foreach loop in the blade.php. I have tried many things but everytime i recevie the same error while using foreachloop

Here is my code Post.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
    @foreach($datafromtestmodel as $rows)
        <li>
            <p>{{$rows['name']}}</p>
            <p>{{$rows['company']}}</p>
            
        </li>
    @endforeach
    </ul>
    
</body>
</html>

Controller Function

public function index()
    {
        $testmodeldata = new testmodel;
        $datafromtestmodel = $testmodeldata ->abc();
        return view('post', compact('datafromtestmodel'));
    }

Model Function

    public function abc(){
        $blabla = ['name' => 'abc', 'company' => 'abc company'];
        return $blabla;
    }

Route

Route::get('post','PostController@index');

CodePudding user response:

As I can see, '$datafromtestmodel' will be single dimensional array, but in blade file, you have treated it as multi dimensional array. This can be fixed in two way. Either return multi dimensional array from model function like this.

public function abc(){
    $blabla = [['name' => 'abc', 'company' => 'abc company']];
    return $blabla;
}

Or you have to update it in your blade file.

    @foreach($datafromtestmodel as $key => $value) //Here $key will be "name" and "company" and $value will be "abc" and "abc company" 
        <li><p>{{$value}}</p></li>
    @endforeach

CodePudding user response:

Your $datafromtestmodel contains ['name' => 'abc', 'company' => 'abc company'] directly.

so when you loop into each item is not an array but directly values ('abc' at first iteration, then 'abc company' at second iteration). They are not array.

To get why you expect your abc function should return an array of array values

public function abc(){
        $blabla = ['name' => 'abc', 'company' => 'abc company'];
        return [$blabla];
    }
  • Related