使用https://github.com/Maatwebsite/Laravel-Excel时出错

时间:2015-04-10 05:59:54

标签: php excel laravel maatwebsite-excel

我正在使用https://github.com/Maatwebsite/Laravel-Excel这个包。当我上传文件时,dd(结果)是

    CellCollection {#842 ▼

         #title: null
        #items: array:4 [▼
         "news_title" => "7th AGM of ADBL today; endorsing 47% cash"            
         "desc" => "The AGM will be endorsing 47% percent cash dividend to its shareholders from the net profit it earned in last fiscal year 2070/71. "
            "link" => "http://www.sharesansar.com/viewnews.php?id=26224&cat=news"
         "stock_code" => "LBL"
        ]
    }

所以,#items包含我的数据,而我不知道为什么输出#title。当我尝试存储我的数据时,由于这个#title,我收到了Integrity Violation Error?那么,有解决方案吗?

这是我存储数据的代码

     public function excelNews()
    {
        if (Input::hasFile('file')) {
            $file = Input::file('file');
            Excel::load($file, function($reader) {
                $reader->setDateFormat('j/n/Y H:i:s');
                $results = $reader->get();
                 foreach ($results as $result)
                {
                    dd($result); // for testing
                    $news = new StockNews;
                    $news->title = $result->news_title;
                    $news->desc = $result->desc;
                    $news->save()
                }

         });
    }
        Flash::success('News has been successfully updated');
        return redirect::back();
    }

错误消息

  

诚信约束违规栏'标题'不能为空

1 个答案:

答案 0 :(得分:1)

发生错误是因为标题为null并尝试将其保存到DB。

有两种方法可以解决问题

在迁移中,将列设置为可为空的

$table->string('title')->nullable();

来源:http://laravel.com/docs/4.2/schema#adding-columns

或检查值,如果为null,则将标题设置为空字符串

$news->title = ($result->news_title) ? $result->news_title : '' ;