/** * Store a newly created resource in storage. * * @param BrandFormRequest $brandForm * * @return \Illuminate\Http\RedirectResponse */ public function store(BrandFormRequest $brandForm) { $input = $brandForm->all(); $account = $this->auth_user->account; if ($brandForm->hasFile('logo') && $brandForm->file('logo')->isValid()) { $input['logo'] = file_get_contents($brandForm->file('logo')->getRealPath()); } else { return Redirect::route('admin.brands.create')->withInput($input)->withErrors(['logo' => 'Something went wrong, while uploading the logo']); } try { if (!$account->isSystemAccount()) { $input['creator_id'] = $account->id; } $brand = Brand::create($input); if (!$brand) { // when we can't save the brand, throw an exception throw new Exception("Couldn't create new brand"); } } catch (Exception $e) { return Redirect::route('admin.brands.create')->withInput($input)->with('message', $e->getMessage()); } return Redirect::route('admin.brands.index')->with('message', 'Brand has been created'); }
/** * Store a newly created resource in storage. * * @param BrandFormRequest $brandForm * @return \Illuminate\Http\RedirectResponse */ public function store(BrandFormRequest $brandForm) { $input = $brandForm->all(); $account = $this->auth_user->account; if ($brandForm->hasFile('logo') && $brandForm->file('logo')->isValid()) { $errors = []; if (!Brand::checkUploadedLogo($brandForm->file('logo'), $errors)) { return Redirect::route('admin.brands.create')->withInput($input)->withErrors(['logo' => $errors]); } // all ok $input['logo'] = file_get_contents($brandForm->file('logo')->getRealPath()); } else { return Redirect::route('admin.brands.create')->withInput($input)->withErrors(['logo' => 'Something went wrong, while uploading the logo']); } try { // begin transaction pass both $input and $account to the closure DB::transaction(function () use($input, $account) { $brand = Brand::create($input); if (!$brand) { // when we can't save the brand, throw an exception throw new Exception("Couldn't create new brand"); } // if our current account isn't the system account, // link the new brand to the current account if (!$account->isSystemAccount()) { $account->brand_id = $brand->id; $result = $account->save(); // when we can't save the account, throw an exception // DB::transaction will automatically rollback if (!$result) { throw new Exception('Something went wrong, while linking the brand to the account'); } } }); } catch (Exception $e) { return Redirect::route('admin.brands.create')->withInput($input)->with('message', $e->getMessage()); } return Redirect::route('admin.brands.index')->with('message', 'Brand has been created'); }