laravel-model-validator

Overview

laravel-model-validator

This is a simple validator.

The validator can be created by command.

The validator has all common table column constraint, eg: string or numeric, max length or min length, etc.

register service

config/app.php - providers

GordenSong\ModelValidatorHelperServiceProvider::class,

create model validator

make:gs-model-validator {model*}


make:gs-model-validator Models/Book

create table validator (TODO)

how to use validator

validator

rule

  • all table field
  • validation type : string, numeric, etc.
  • string(length:50): max:50
  • auto increment: min:1
  • nullable
  • not required
  • self define

method

with(array $data) : self

data to deal with.


required(...$fields) : self

fields in params list add required


`only(...$fields) : self:

only fields can be validated.


exclude(...$field) : self

$fields will not be validated.


passes() : bool

fails() : bool

validate() : array | throw ValidationException

validated() : array | throw ValidationException

BooksValidator

migration
Schema::create('books', function (Blueprint $table) {
    $table->id();
    $table->string('title', 50)->nullable();
    $table->integer('price')->nullable()->default(0);
});
validator
class BooksValidator extends ModelValidator
{
    protected $rules = [
        'id' => [
            'numeric',
            'min:1',
        ],
        'title' => [
            'string',
            'max:50',
            'nullable',
        ],
        'price' => [
            'numeric',
            'min:0',
            'nullable',
        ],
    ];

    protected $customerAttributes = [

    ];
}

controller

class BookController extends Controller
{
    public function store(Request $request, BooksValidator $validator)
    {
        $data = $validator
            ->with($request->all())
            ->validated();

        $book = Books::query()->create($data);

        return $book->toArray();
    }

    public function storeRequireTitlePrice(Request $request, BooksValidator $validator)
    {
        $data = $validator
            ->with($request->all())
            ->required('title', 'price')
            ->validated();

        $book = Books::query()->create($data);

        return $book->toArray();
    }

    public function updateOnlyPrice(Request $request, BooksValidator $validator)
    {
        $data = $validator
            ->with($request->all())
            ->only('price')
            ->validated();

        $book = Books::query()->findOrFail($request->id);
        $book->update($data);

        return $book->toArray();
    }

    public function updateExcludePrice(Request $request, BooksValidator $validator)
    {
        $data = $validator
            ->with($request->all())
            ->exclude('price')// 排除
            ->validated();

        $book = Books::query()->findOrFail($request->id);
        $book->update($data);

        return $book->toArray();
    }
}
test
class BookControllerTest extends TestCase
{
    use DatabaseTransactions;

    public function testStoreValidate()
    {
        $data = ['title' => Str::random(60)];

        $response = $this->postJson(route('book.store'), $data);
        $response->assertStatus(422);

        $data = ['price' => -1];

        $response = $this->postJson(route('book.store'), $data);
        $response->assertStatus(422);

        $data = [];

        $this->withoutExceptionHandling();
        try {
            $response = $this->postJson(route('book.store'), $data);
            self::fail('InvalidArgumentException');
        } catch (\Exception $e) {
            self::assertInstanceOf(\InvalidArgumentException::class, $e);
        }
    }

    public function testStoreValidate_argument_too_many()
    {
        $data = [
            'title' => $title = 'old title',
            'author' => Str::random(30),
            'hehe' => 'haha',
        ];

        $response = $this->postJson(route('book.store'), $data);
        $response->assertOk();
        $response->assertJsonStructure(['title', 'id']);
        $response->assertJsonFragment(['title' => $title]);
    }

    public function testStoreRequireTitlePrice()
    {
        $data = [
            'title' => 'aaa',
        ];
        $response = $this->postJson(route('book.store.require-title-price'), $data);
        $response->assertStatus(422);

        $data = [
            'title' => 'aaa',
            'price' => 111,
        ];
        $response = $this->postJson(route('book.store.require-title-price'), $data);
        $response->assertOk();
    }

    public function testUpdateOnlyPrice()
    {
        $book = factory(Books::class)->create([
            'price' => $oldPrice = 100,
            'title' => $oldTitle = 'old title',
        ]);

        $data = [
            'id' => $book->id,
            'title' => $newTitle = 'new title',
            'price' => $newPrice = 200
        ];
        $response = $this->postJson(route('book.update.only-price'), $data);
        $response->assertOk();

        $book->refresh();

        self::assertEquals($newPrice, $book->price);
        self::assertEquals($oldTitle, $book->title);
    }

    public function test_updateExcludePrice()
    {
        /** @var Books $book */
        $book = factory(Books::class)->create([
            'price' => $oldPrice = 100,
            'title' => $oldTitle = 'old title',
        ]);

        $data = [
            'id' => $book->id,
            'title' => $newTitle = 'new title',
            'price' => $newPrice = 200
        ];
        $response = $this->postJson(route('book.update.exclude-price'), $data);
        $response->assertOk();

        $book->refresh();

        self::assertEquals($newTitle, $book->title);
        self::assertEquals($oldPrice, $book->price);
    }
}
You might also like...
Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

This Laravel package merges staudenmeir/eloquent-param-limit-fix and staudenmeir/laravel-adjacency-list to allow them being used in the same model.

Easily create a revision history for any laravel model
Easily create a revision history for any laravel model

Wouldn't it be nice to have a revision history for any model in your project, without having to do any work for it. By simply adding the RevisionableT

Automatic Laravel model migrations.

Laravel Automatic Migrations Automatic Laravel model migrations. Instead of having to create and manage migration files, this package allows you to sp

Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Laravel Quran is static Eloquent model for Quran.

Laravel Quran بِسْمِ ٱللّٰهِ الرَّحْمٰنِ الرَّحِيْمِ Laravel Quran is static Eloquent model for Quran. The Quran has never changed and never will, bec

Save Model is a Laravel package that allows you to save data in the database in a new way.

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about $guarded and $fillable properties in the model anymore. Just relax an use Save Model package.

PHP 8 attribute to register Laravel model observers.

PHP 8 attribute to register Laravel model observers. Instead of defining observers inside service providers this package offers an alternative way to

Owner
null
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
This is a simple url bot validator made with laravel and react

?? This is a simple URL validator. Used Technologies React - Javascript framework Laravel - PHP framework Mysql - Relational database Installation Ins

Vanderson Telema 1 Oct 27, 2021
Laravel Disposable Email Validator

Laravel Disposable Email Validator Prevent users from registrering with a disposable email addresses! Table of Contents Installation Usage Translation

Tim Wassenburg 2 Oct 12, 2022
Laravel Common Password Validator

laravel-common-password-validator Laravel Common Password Validator An optimized and secure validator to check if a given password is too common. By d

WedgeHR 1 Nov 6, 2021
Laravel Dutch Phone Number Validator

Laravel Dutch Phone Number Validator Validate if the given phone number is a valid Dutch phone number Table of Contents Installation Usage Translation

Tim Wassenburg 0 May 30, 2022
A simple validator package to check if the given zipcode has a valid Dutch zipcode format

Laravel Dutch Zipcode Validator A simple validator package to check if the given zipcode has a valid Dutch zipcode format Table of Contents Installati

Tim Wassenburg 0 May 30, 2022
EmailValidator - PHP Email address validator

EmailValidator A library for validating emails against several RFC. Supported RFCs This library aims to support RFCs: 5321, 5322, 6530, 6531, 6532, 10

Eduardo Gulias Davis 10.9k Jan 3, 2023
A Laravel package that adds a simple image functionality to any Laravel model

Laraimage A Laravel package that adds a simple image functionality to any Laravel model Introduction Laraimage served four use cases when using images

Hussein Feras 52 Jul 17, 2022