testuser
testuser

Reputation: 11

Laravel foreach loop is not working in a view

My controller

public function showWelcome()
{
        $data = Category::select();
        return View::make('hello',$data);

}

controller result array

array(3) {
  [0]=>
  object(stdClass)#137 (4) {
    ["id"]=>
    int(1)
    ["category_name"]=>
    string(8) "everyone"
    ["category_image"]=>
    string(36) "7e14fecb5b45941dd9bcff3497c57d1a.png"
    ["start_date"]=>
    string(10) "2014-09-10"
  }
  [1]=>
  object(stdClass)#138 (4) {
    ["id"]=>
    int(2)
    ["category_name"]=>
    string(12) "motivational"
    ["category_image"]=>
    string(36) "99b8dfff667da7a7e9e39e514e3342bd.png"
    ["start_date"]=>
    string(10) "2014-09-09"
  }
  [2]=>
  object(stdClass)#139 (4) {
    ["id"]=>
    int(3)
    ["category_name"]=>
    string(4) "racy"
    ["category_image"]=>
    string(36) "3a213b108c30184a3f416239473a3880.png"
    ["start_date"]=>
    string(10) "2014-09-10"
  }
}

my view

@foreach($data as $fetch)
    {{ $fetch->id }}
@endforeach

I am trying to show my data array value in view but not work.show a error

Undefined variable: data (View: C:\Users\shanto\my-project\app\views\hello.blade.php)

I am new in laravel .I cant understand whats my wrong.

Upvotes: 1

Views: 1777

Answers (2)

Laurence
Laurence

Reputation: 60048

Change

public function showWelcome()
{
        $data = Category::select();
        return View::make('hello',$data);
}

to

public function showWelcome()
{
        $data = Category::select();
        return View::make('hello')->with('data', $data);
}

or you can do

return View::make('hello')->withData($data);

Upvotes: 0

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

in your controller function

return View::make('hello')->with(array('data'=>$data));

Since your controller sends values inside of data array making them variable for view file. you need to include $data inside of an array and send to view.

Upvotes: 1

Related Questions