使用compact从控制器传递数组以查看laravel

I'm using laravel 5.3 (make:auth automatic register and user authentication generator), and I would like to let user choose their tags in the registration form.

I wanna pass $tags = App\Tag::all(); to the register.blade.php file located in views\authegister.blade.php.

I found this method:

public function showRegistrationForm()
{
    return view('auth.register');
}

and I would like to do:

public function showRegistrationForm()
{
    $tags = App\Tag::all();
    return view('auth.register', compact($tags));
}

but I get undefined variable 'tags' when trying to reach the register.blade.php file.

Don't feed the variable itself, provide the variable name when using compact.

return view('auth.register', compact('tags'));

First you need to know this :

Models , Views , Controller ;

the controller is the center point ie gets data from model and passes the data to the view , or plain view .So what does this mean :

public function showRegistrationForm()
    {
        return view('auth.register');
    }

this here returns a plain view .And this below returns a view with the model data , in your case App\Tag: and App\Tag::all() is a collection ie a container with a dataset ;

public function showRegistrationForm()
    {
        $tags = App\Tag::all();
        return view('auth.register', compact($tags));
    }

or better yet instead of compacting the array just create a new array and pass the dataset , how ?

return view('auth.register', ['tags' => $tags]);

Here is how to debug your app :Use below method :

public function showRegistrationForm()
    {
        $tags = App\Tag::all();
        dd($tags);
        //return view('auth.register', compact($tags));
    }

Do you see an array or error ? if array then your dataset is being passed to view , if not then there is an error either that the model does not exist or something , just check your log file .

Good Luck.

if you want use compact then use like this

 return view('auth.register', compact('tags'));

in laravel 5.3 they have change like below but even you can use both methods :)

return view('auth.register', ['tags' => $tags]);