在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):dwightwatson/validating开源软件地址(OpenSource Url):https://github.com/dwightwatson/validating开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):Validating, a validation trait for LaravelValidating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria before being saved. If they are not considered valid the model will not be saved and the validation errors will be made available. Validating allows for multiple rulesets, injecting the model ID into Laravel 4.2+Looking to use Validating on Laravel 4.2+? Take a look at the 0.10.x branch for documentation and installation instructions. The Laravel 4.2 version is better suited to doing form validation; it supports custom validation messages, confirmation rules and multiple rulesets. Because Laravel 5.0 has Laravel 5.0 - 5.2Looking to use Validating on Laravel 5.0 to 5.2? Take a look at the 2.x branch for documentation and installation instructions. The Laravel 5.0 - 5.2 version used a since-deprecated Laravel 5.3+Just read on - these instructions are for you! InstallationSimply go to your project directory where the composer require watson/validating View installation instructions for Laravel 4.2+. View installation instructions for Laravel 5.0 - 5.2. OverviewFirst, add the trait to your model and add your validation rules and messages as needed. use Watson\Validating\ValidatingTrait;
class Post extends Eloquent
{
use ValidatingTrait;
protected $rules = [
'title' => 'required',
'slug' => 'required|unique:posts,slug',
'content' => 'required'
];
} You can also add the trait to a Note: you will need to set the Now, you have access to some pleasant functionality. // Check whether the model is valid or not.
$post->isValid(); // true
// Or check if it is invalid or not.
$post->isInvalid(); // false
// Once you've determined the validity of the model,
// you can get the errors.
$post->getErrors(); // errors MessageBag Model validation also becomes really simple. if ( ! $post->save()) {
// Oops.
return redirect()->route('posts.create')
->withErrors($post->getErrors())
->withInput();
}
return redirect()->route('posts.show', $post->id)
->withSuccess("Your post was saved successfully."); Otherwise, if you prefer to use exceptions when validating models you can use the $post->saveOrFail(); You don't need to catch the exception, if you don't want to. Laravel knows how to handle a try {
$post->saveOrFail();
} catch (Watson\Validating\ValidationException $e) {
$errors = $e->getErrors();
return redirect()->route('posts.create')
->withErrors($errors)
->withInput();
} Note that you can just pass the exception to the Bypass validationIf you're using the model and you wish to perform a save that bypasses validation you can. This will return the same result as if you called $post->forceSave(); Validation exceptions by defaultIf you would prefer to have exceptions thrown by default when using the /**
* Whether the model should throw a ValidationException if it
* fails validation. If not set, it will default to false.
*
* @var boolean
*/
protected $throwValidationExceptions = true; If you'd like to perform a one-off save using exceptions or return values, you can use the Validation messagesTo show custom validation error messages, just add the /**
* Validation messages to be passed to the validator.
*
* @var array
*/
protected $validationMessages = [
'slug.unique' => "Another post is using that slug already."
]; Unique rulesYou may have noticed we're using the You can adjust this functionality by setting the /**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true; Out of the box, we support the Laravel provided It's easy to support additional injection rules too, if you like. Say you wanted to support an additional rule you've got called /**
* Prepare a unique_ids rule, adding a model identifier if required.
*
* @param array $parameters
* @param string $field
* @return string
*/
protected function prepareUniqueIdsRule($parameters, $field)
{
// Only perform a replacement if the model has been persisted.
if ($this->exists) {
return 'unique_ids:' . $this->getKey();
}
return 'unique_ids';
} In this case if the model has been saved and has a primary key of EventsVarious events are fired by the trait during the validation process which you can hook into to impact the validation process. To hook in, you first need to add the /**
* User exposed observable events
*
* @var array
*/
protected $observables = ['validating', 'validated']; When validation is about to occur, the Event::listen('eloquent.validating:*', function($model, $event) {
// Pseudo-Russian roulette validation.
if (rand(1, 6) === 1) {
return false;
}
}); After validation occurs, there are also a range of TestingThere is currently a bug in Laravel (see issue #1181) that prevents model events from firing more than once in a test suite. This means that the first test that uses model tests will pass but any subseqeuent tests will fail. There are a couple of temporary solutions listed in that thread which you can use to make your tests pass in the meantime. Since Laravel has switched to Liferaft for the purpose of tracking bugs and pull requests, the issue mentioned above may not be available. This Gist has an example Controller usageThere are a number of ways you can go about using the validating validating model in your controllers, however here is one example that makes use of the new FormRequest in Laravel 5 (if you'd like to see another controller example without the FormRequest, check the 4.2+ version of this package. This example keeps your code clean by allowing the FormRequest to handle your form validation and the model to handle its own validation. By enabling validation exceptions you can reduce repetitive controller code (try/catch blocks) and handle model validation exceptions globally (your form requests should keep your models valid, so if your model becomes invalid it's an exceptional event). <?php namespace App\Http\Controllers;
use App\Http\Requests\PostFormRequest;
use Illuminate\Routing\Controller;
class PostsController extends Controller
{
protected $post;
public function __construct(Post $post)
{
$this->post = $post;
}
// ...
public function store(PostFormRequest $request)
{
// Post will throw an exception if it is not valid.
$post = $this->post->create($request->input());
// Post was saved successfully.
return redirect()->route('posts.show', $post);
}
} You can then catch a model validation exception in your public function render($request, Exception $e)
{
if ($e instanceof \Watson\Validating\ValidationException) {
return back()->withErrors($e)->withInput();
}
parent::render($request, $e);
} |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论