Laravel 5.4 - 检查所有模型插入和更新是否正常

时间:2017-04-26 11:30:57

标签: laravel-5.4

我正在更新文件并将其插入到DB中的3个表中。我想检查一切是否正常,如果没有抛出错误,那么如果上传正常,我可以向用户显示成功消息。我怎么能这样做?

这是我的代码:

public function upload(Request $request)
  {
    if ($request->hasFile('csvFile')) {
      $file = $request->file('csvFile');
      $file->move('uploads', $file->getClientOriginalName());
      $this->store($file);
    }

    Session::flash('flash_message','File was successfully uploaded.');

    return view('home');
  }

  public function store($file)
  {
    $path = base_path('public/uploads/' .$file->getClientOriginalName());
    $rows = Excel::load($path, function($reader) { })->get()->toArray();

    foreach($rows as $row) {

      $id = $row[4];
      $shopeTitle = $row[1];
      $price = $row[6];
      $mall = $row[5];
      $visitors = $row[3];

      Shop::updateOrCreate(
        ['id' => $id],
        ['title' => $shopeTitle]
      );

      Mall::where('id', $id)->update([
        'price' => $price,
        'visitors' => $visitors
      ]);

      if ($mall != 41 || $mall!= 42) {
        DB::table('store_mall')->insert([
          'mall' => $price,
          'store' => $id
        ]);
      }
    }
  }

1 个答案:

答案 0 :(得分:0)

我认为你应该使用交易。 你可以做这样的事情

try {
    DB::beginTransaction();

    //your insert updates here

    //if everything ok commit transaction
    DB::commit();
} catch (Exception $ex) {
    //if errors exist roll back transaction
    DB::rollBack();
}

您可以在Laravel DB Transactions

中阅读更多信息