我试图创建一个帮助器来集中复杂的Form :: select。
我的帮手:
namespace App\Helpers;
use Log;
use App\Countries;
class Address {
public static function country() {
$countries = Countries::orderby('name_zh','asc');
$form = "Form::select('countries', \$countries);";
return $form;
}
}
我的观点:
{!! Address::country() !!}
我想从这个帮助器中选择带有$countries
变量的选择表单,并在我的视图中显示一个下拉列表。我该怎么做?
答案 0 :(得分:1)
在你的助手中使用Laravel Collective帮助器创建select,将它返回到视图中,这样做:
public static function country() {
$countries = Countries::orderby('name_zh','asc')
->pluck('name', 'id');
return Form::select('countries', $countries);
}
在视图中只需调用方法:
{{ Address::country() }}
或者,如果你想要$countries
变量,你可以将它从控制器发送到视图,然后将它发送给帮助者:
public function controllerFunction() {
$countries = Countries::orderby('name_zh','asc')
->get();
return view('yourView')->withCountries($countries);
}
在视图中,您可以访问此$countries
,然后将其传递给帮助程序:
{{ Address::country($countries->pluck('name', 'id')) }}
这次的助手应该是这样的:
public static function country($countries) {
return Form::select('countries', $countries);
}
答案 1 :(得分:0)
不确定真正理解你的问题......
但是如果你想将$countries
变量传递给你的视图,你的函数必须简单地返回这个变量。
public static function country()
{
$countries = ...;
return $countries;
}
然后,有两个选择:
将您的功能用于控制器
use App\Helpers\Address;
// code code code
public function controllerFunc()
{
// code
$countries = Address::country();
return view('yourview', compact($countries));
}
并在你看来:
<!-- Dump your $countries (from controller) var -->
{{ dd($countries) }}
将您的功能用于您的视图
<!-- Dump your $countries (from helper) var -->
{{ dd(\App\Helpers\Address::country()) }}
现在,如果你想直接传递你的选择,那么在静态函数中,像Maraboc一样返回Form::select('countries', $countries')
。