Example #1
0
 /**
  * Save resource to the data base using transactions.
  *
  * @param  string $action
  *
  * @return Response
  */
 protected function persist($action)
 {
     try {
         DB::beginTransaction();
         // Validate resource relationships
         if ($this->relationships) {
             list($labels, $rules) = \App\Validation\Validator::parseRules($this->relationships);
             $validator = Validator::make(Input::only(array_keys($rules)), $rules)->setAttributeNames($labels);
             if ($validator->fails()) {
                 $this->resource->validate();
                 $this->resource->getErrors()->merge($validator->messages()->toArray());
                 throw new ModelValidationException(_('Wrong relationships data'));
             }
         }
         // Validate and save resource
         if ($this->resource->save() === false and $this->resource->getErrors()->count()) {
             throw new ModelValidationException(_('Wrong data'));
         }
         // Save resource relationships
         foreach ($this->relationships as $relationship => $notUsed) {
             $this->resource->{$relationship}()->sync(Input::get($relationship, []));
         }
         // Success :)
         DB::commit();
         if ($action === 'update') {
             $successMesssage = _('%s successfully updated');
         } elseif ($action === 'store') {
             $successMesssage = _('%s successfully created');
         } else {
             $successMesssage = _('%s successfully saved');
         }
         Session::flash('success', sprintf($successMesssage, $this->resource));
         return redirect()->route("{$this->prefix}.show", [$this->resource->getKey()]);
     } catch (\Exception $e) {
         DB::rollBack();
         if ($e instanceof ModelValidationException) {
             Session::flash('error', $e->getMessage());
         } else {
             throw $e;
         }
         // Unexpected exception, re-throw it to be able to debug it.
         return redirect()->back()->withInput()->withErrors($this->resource->getErrors());
     }
 }