错误:laravel 视图中未定义的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41809412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error : undefined variable in laravel view
提问by Naj
I am getting this error: undefined variable. I read a lot of posts about it but, none of them helped with the problem i am facing. (Why I get "Undefined variable" in Laravel view?)
我收到此错误:未定义的变量。我阅读了很多关于它的帖子,但没有一个对我面临的问题有帮助。(为什么我在 Laravel 视图中得到“未定义的变量”?)
This is Project_Controller :
这是 Project_Controller :
class Project_Controller extends Controller
{
public function create()
{
$arrondissement = Arrondissements::pluck('arrondissement', 'id');
return view::make('projets.create', compact('arrondissement'));
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'intitule' => 'required|max:255',
'code' => 'required|max:255',
'dateDebut' => 'required|max:255',
'dateFin' => 'required|max:255',
'estimation' => 'required|max:255',
'arrondissement' => $request->arrondissement,
]);
if ($validator->fails()) {
return back()
->withInput()
->with(['arrondissement'=>$arrondissement])
->withErrors($validator);
}
$projet = new Projet;
$projet->intitule = $request->intitule;
$projet->code = $request->code;
$projet->dateDebut = $request->dateDebut;
$projet->dateFin = $request->dateFin;
$projet->estimation = $request->estimation;
$projet->arrondissement = $request->arrondissement;
$projet->save();
return view('/submit', compact('arrondissement'));
}
}
submit.blade.php :
提交.blade.php :
<select name="arrondissement_id">
@if (!empty($arrondissement))
Whoops! Something went wrong
@else
@foreach($arrondissement as $id => $arrondissement)
<option value="{{$id}}">{{$arrondissement}}</option>
@endforeach
@endif
</select>
and this is routes.php :
这是 routes.php :
Auth::routes();
Route::get('/home', 'HomeController@index');
Route::get('/', function () {
$projets = \App\Projet::all();
return view('welcome', compact('projets'));
});
Route::get('/submit', function () {
return view('submit');
});
Route::post('submit/projects', 'Project_Controller@store');
I can't see what's causing this error ??
我看不出是什么导致了这个错误??
I am using 'arrondissement' as a foreign key of table 'arrondissements'
我使用“arrondissement”作为表“arrondissements”的外键
采纳答案by Naj
I solved the problem. It's simple, I had to remove exclamation mark. Because, I need to test if the value is empty not unempty.
我解决了这个问题。很简单,我必须去掉感叹号。因为,我需要测试该值是否为空而不是非空。
回答by Alexey Mezenin
When returning the view, you should also pass the variable with data:
返回视图时,您还应该传递带有数据的变量:
$arrondissement = ....
return view('/submit', compact('arrondissement'));
回答by adesh kumar
$arrondissement = Arrondissements::pluck('arrondissement', 'id');
You should also add this line into the store function
您还应该将此行添加到商店功能中