0
votes

Here is my controller code:

$exam_categories = ExamCategory::all();
return view('test.test-home')->withExamCategories($exam_categories);

Here is my blade template code:

<select class="custom-select form-control-lg exam-category" id="exam-category" style="font-weight: bold">
     <option selected>Select</option>
     @foreach($exam_categories as $examCategory)
          <option value="{{$examCategory->id}}">{{$examCategory->Category}}</option>
     @endforeach
</select>

If I run this code then it shows the following error:

Undefined variable: exam_categories (View: /var/www/myproj/resources/views/test/test-home.blade.php)

It was working fine in laravel 5.4 version, but when I updated to laravel 5.8, it is not working.

2

2 Answers

2
votes

Try using compact instead.

 $exam_categories = ExamCategory::all();
    return view('test.test-home', compact('exam_categories'));

OR

 $exam_categories = ExamCategory::all();
    return view('test.test-home')->with(['exam_categories' => $exam_categories]);
1
votes

Here is 2 way to pass data to view:

  1. $exam_categories = ExamCategory::all();
    return view('test.test-home')->with('exam_categories',$exam_categories);
    
  2. $exam_categories = ExamCategory::all();
    return view('test.test-home',['exam_categories',$exam_categories]);
    

Now you can easily access a variable in a view using $exam_categories.

For more information, you can read documentation here