/** * Class constructor. * * Initialize class properties. * * @param string $title Title of the report * @param string $view View file for showing the results * @param array $fields Form fields labels and validation rules * @param array $input Default form input * @param string $offCanvasClass Class to apply to the off-canvas * * @return void */ public function __construct($title, $view, array $fields, array $input, $offCanvasClass = null) { // Setup layout parent::__construct(); $this->title = $title; $this->view = $view; list($this->labels, $this->rules) = \App\Validation\Validator::parseRules($fields); $this->defaultInput = $input; $this->offCanvasClass = $offCanvasClass; }
/** * Set validation rules and labels. * * @param array * * @return Model */ protected function setRules(array $rules) { list($this->labels, $this->rules) = \App\Validation\Validator::parseRules($rules); return $this; }
/** * 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()); } }