简体   繁体   English

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

[英]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. 我正在使用laravel 5.3(make:auth自动注册和用户身份验证生成器),我想让用户在注册表单中选择他们的标签。

I wanna pass $tags = App\\Tag::all(); 我想传递$tags = App\\Tag::all(); to the register.blade.php file located in views\\auth\\register.blade.php . 到位于views\\auth\\register.blade.phpregister.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. 但是在尝试访问register.blade.php文件时出现未定义的变量'tags'

不要输入变量本身,在使用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 ; 这将返回一个普通视图。下面将返回一个包含模型数据的视图,在您的情况下App\\Tag:App\\Tag::all()是一个集合,即一个带有数据集的容器;

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 :) 在laravel 5.3中,它们具有如下所示的更改,但即使您可以同时使用两种方法:)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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