【问题标题】:Call to a member function getRealPath() on null在 null 上调用成员函数 getRealPath()
【发布时间】:2018-04-04 12:13:13
【问题描述】:

我想问一下,如果没有上传文件但他们按下了上传按钮,我该如何输入错误消息。如果 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();
        }

    }

【问题讨论】:

  • 对您的文件进行适当的验证

标签: laravel laravel-5 laravel-5.5


【解决方案1】:

你可以在调用 getRealPath() 函数之前加上一个 if

if( Input::file('import_file') ) {
    $path = Input::file('import_file')->getRealPath();
} else {
    return back()->withErrors(...);
}

【讨论】:

    【解决方案2】:

    您可以设置如下错误信息

    return redirect()->back()->with('errors', 'No file selected');

    然后像 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2019-01-30
      • 2020-03-10
      • 2017-09-24
      相关资源
      最近更新 更多