Home > Net >  Undefined foreach variable laravel
Undefined foreach variable laravel

Time:03-10

hello guys im having a problem with passing variable from my controller to views, as it does not identify its variable, here is my code:

RegisterController.php

use App\angkatan;
public function index()
    {            
        $select = Angkatan::all();
        return view('/auth/register')->with('name', $select);
    }

My Route

web.php

Route::get('register', 'RegisterController@index');

and my view

register

@foreach($name as $ps)
@endforeach

the error say

Undefined variable: name (0)

im very thankful if anyone can help

CodePudding user response:

You are just passing the wrong way $select variable to your view.

when you use Illuminate\View\View::with method you should pass an associative array which as key => value pairs

  return view('/auth/register')->with(['name' => $select]);

You can also use compact which allows to pass variable which are accessible inside of the scope of your controller to the view and the string passed as argument to that function will be the name of variable accessible inside of the view file

$select = Angkatan::all();
return view('/auth/register', compact('select'));

CodePudding user response:

You can not pass the variable in this way to the view. You have to pass an array in the second parameter of the with() method - it should be something like this:

return view('greeting', ['name' => 'James']);

CodePudding user response:

    return view('/auth/register', ['name' => $select]);

you can pass a second massive parameter to the view, and also in with method, you need to pass massive as I remember.

  • Related