我很困惑如何将变量从控制器传递到视图.我知道有很多关于这个已经在库存溢出,但无法找到一个有效的,请指出我正确的方向.谢谢.
CONTROLLER
class StoreController extends Controller
{
public function index()
{
$store = Store::all(); // got this from database model
return view('store', $store);
}
{
Run Code Online (Sandbox Code Playgroud)
视图
// try a couple of differnt things nothing works
print_r($store);
print_r($store[0]->id);
print_r($id);
Run Code Online (Sandbox Code Playgroud)
Jil*_*mas 25
public function index()
{
$store = Store::all(); // got this from database model
return view('store')->with('store', $store);
}
Run Code Online (Sandbox Code Playgroud)
一般来说,你有三种选择.
return view('store')->with('store', $store);
return view('store')->withStore($store);
return view('store')->with(compact('store'));
1.创建一个名为的变量store,该变量将在您view的变量$store中存储并将值存储在变量中.
2.对于上面的一个.
3.也是一个简短的手,它创建与传递值相同的变量名.
现在,您view可以使用以下方式访问此变量
{{ $store->name }}
对于所有3种方法都是一样的.
尝试这个
public function index()
{
return view('store', ['store' => Store::all()]);
}
Run Code Online (Sandbox Code Playgroud)
然后您可以在您的评论中访问 $store。
更新:如果您已经在代码中定义了变量并希望在视图中使用相同的名称,您也可以使用compact方法。
例子:
public function index()
{
$store = Store::all();
return view('store', compact('store'));
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这个对我有用。您可以像这样使用“紧凑”:
控制器:
class StoreController extends Controller
{
public function index()
{
$store = Store::all(); // 'don't forget' use App\Driver;
return view('store', compact('store'));
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记图书馆: use App\Store;
看法:
在视图中,您有一个包含所有数据的数组,只需调用{{ $store }}
如果您想要特定数据,请使用以下内容:
@foreach($store as $data)
{{ $data->name }}
@endforeach
Run Code Online (Sandbox Code Playgroud)
不要忘记使用 Laravel 的“Forms & HTML”,这里是文档的链接:https ://laravel.com/docs/4.2/html
| 归档时间: |
|
| 查看次数: |
43921 次 |
| 最近记录: |