-
-
Save RimonEkjon/547cccd77b01300b9cf8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class BaseModel extends Eloquent | |
{ | |
public $timestamps = false; | |
/** | |
* Validation rules | |
* | |
* @var array | |
*/ | |
protected $rules = []; | |
/** | |
* Validate the model or the data passed to the method. | |
* | |
* <code> | |
* $user = new User; | |
* $user->fill($data); | |
* $user->validate(); | |
* $user->save(); | |
* </code> | |
* or | |
* <code> | |
* $user = new User; | |
* $user->validate($data); | |
* $user->fill($data); | |
* $user->save(); | |
* </code> | |
* | |
* | |
* @param array $data | |
* @return bool | |
* @throws ValidationException | |
*/ | |
public function validate($data = null) | |
{ | |
if (is_null($data)) { | |
$data = $this->toArray(); | |
} | |
$validator = Validator::make($data, $this->rules); | |
if ($validator->fails()) { | |
throw new ValidationException($validator); | |
} | |
// Validator passed | |
return true; | |
} | |
public function validateSave($data) { | |
try { | |
$this->fill($data); | |
$this->validate(); | |
$this->save(); | |
} catch (ValidationException $e) { | |
throw $e; | |
} | |
} | |
} | |
/** | |
* @link http://net.tutsplus.com/tutorials/javascript-ajax/combining-laravel-4-and-backbone/ Combining Laravel 4 and Backbone | |
*/ | |
class ValidationException extends Exception { | |
protected $messages; | |
/** | |
* We are adjusting this constructor to receive an instance | |
* of the validator as opposed to a string to save us some typing | |
* @param Validator $validator failed validator object | |
*/ | |
public function __construct($validator) | |
{ | |
$this->messages = $validator->messages(); | |
parent::__construct($this->messages, 400); | |
} | |
public function getMessages() | |
{ | |
return $this->messages; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment