0

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');

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.