简体   繁体   中英

Passing an array from controller to view laravel using compact

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\\auth\\register.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.

不要输入变量本身,在使用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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM