'Laravel undefined variable but it is

I have a problem "Undefined variable $medzisklads", this is code of my print from databases, variable $medzisklads is undefined but I have defined in MedziskladController in index.I have 3 Models Sklad, Medzisklad and Vydajsklad. And I used this same code for Sklad with change variables, which I use for Sklad and it works. But for Medzisklad and Vydajsklad dont work and show me error with undefined variable. enter image description here

This is my foreach in index.blade.php.

 @foreach($medzisklads as $medzisklad)
   <br>
        {{$medzisklad->medzidatle}} {{$medzisklad->medzimandle}} {{$medzisklad->medzimarcipan}} {{$medzisklad->medziorechy}}
           
   @endforeach

and this is my MedziskladController

public function index()
{
    $medzisklads = Medzisklad::all();
   return view('sklads.index')-> with('medzisklads', $medzisklads);
}

and this is my route

Route::resource('medzisklad', 'App\Http\Controllers\MedziskladController');

Medzisklad is model in databases.



Solution 1:[1]

pass array in with the method

public function index()
{
   $medzisklads = Medzisklad::get();
   return view('sklads.index')->with(['medzisklads' => $medzisklads]);
}

Solution 2:[2]

Try this

public function index()
{
   $medzisklads = Medzisklad::get();
   return view('sklads.index', compact('medzisklads'));
}

Solution 3:[3]

Try this

public function index()
   {
       $medzisklads = Medzisklad::get();
       return view('sklads.index', ['medzisklads'=>$medzisklads]);
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jignesh Joisar
Solution 2 sujit prasad
Solution 3 Ajay Kumar