laravel 在 null 上调用成员函数 getRealPath()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49642497/
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
Call to a member function getRealPath() on null
提问by gwapo
I wanted to ask on how can i put a error message if theres no uploaded file but they press the upload button. How can I put an error message if the getRealPath is empty?
我想问一下,如果没有上传的文件,我该如何放置错误消息,但他们按下了上传按钮。如果 getRealPath 为空,我如何放置错误消息?
public function importExcel()
{
if (empty(Input::file('import_file')->getRealPath())) {
return back()->with('success','No file selected');
}
else {
$path = Input::file('import_file')->getRealPath();
$inserts = [];
Excel::load($path,function($reader) use (&$inserts)
{
foreach ($reader->toArray() as $rows){
foreach($rows as $row){
$inserts[] = ['biometrics' => $row['biometrics'], 'first_name' => $row['first_name'], 'last_name' => $row['last_name'], 'date' => $row['date'], 'emp_in' => $row['emp_in'], 'emp_out' => $row['emp_out']];
}
}
});
if (!empty($inserts)) {
DB::table('attendances')->insert($inserts);
return back()->with('success','Inserted Record successfully');
}
return back();
}
}
回答by dynero
You can put an if before calling the getRealPath() function
您可以在调用 getRealPath() 函数之前放置一个 if
if( Input::file('import_file') ) {
$path = Input::file('import_file')->getRealPath();
} else {
return back()->withErrors(...);
}
回答by Nirali
You can set error message like below
您可以设置如下错误消息
return redirect()->back()->with('errors', 'No file selected');
return redirect()->back()->with('errors', 'No file selected');
And then show error message in blade like mention in laravel documention. It store message in session and you can easily show sesssion messages in blade file like below
然后在刀片中显示错误消息,就像在 laravel 文档中提到的那样。它将消息存储在会话中,您可以轻松地在刀片文件中显示会话消息,如下所示
@if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger error">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif