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);
    }
}
Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable Easy creation of slugs for your Eloquent models in Laravel. NOTE: These instructions are for the latest version of Laravel. If you

Colin Viebrock 3.2k Jun 14, 2021
Please see the Diglactic fork.

Update: 18 October 2020 There is now an official fork of Laravel Breadcrumbs: https://github.com/diglactic/laravel-breadcrumbs Blog post: https://news

Dave James Miller 2.4k Jun 17, 2021
An Eloquent Way To Filter Laravel Models And Their Relationships

Eloquent Filter An Eloquent way to filter Eloquent Models and their relationships Introduction Lets say we want to return a list of users filtered by

Eric Tucker 1.2k Jun 18, 2021
Automatically validating Eloquent models for Laravel

Validating, a validation trait for Laravel Validating is a trait for Laravel Eloquent models which ensures that models meet their validation criteria

Dwight Watson 918 Jun 8, 2021
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

Venture Craft 2.2k Jun 20, 2021
This package gives Eloquent models the ability to manage their friendships.

Laravel 5 Friendships This package gives Eloquent models the ability to manage their friendships. You can easily design a Facebook like Friend System.

Alex Kyriakidis 655 Jun 5, 2021
Laravel package to generate and to validate a UUID according to the RFC 4122 standard. Only support for version 1, 3, 4 and 5 UUID are built-in.

Laravel Uuid Laravel package to generate and to validate a universally unique identifier (UUID) according to the RFC 4122 standard. Support for versio

Christoph Kempen 1.7k Jun 16, 2021
Laravel Ban simplify blocking and banning Eloquent models.

Laravel Ban Introduction Laravel Ban simplify management of Eloquent model's ban. Make any model bannable in a minutes! Use case is not limited to Use

cybercog 614 Jun 4, 2021
Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be.

VatCalculator Handle all the hard stuff related to EU MOSS tax/vat regulations, the way it should be. Integrates with Laravel and Cashier — or in a st

Dries Vints 932 Jun 15, 2021
A simple Content Moderation System for Laravel 5.* that allows you to Approve or Reject resources like posts, comments, users, etc.

Laravel Moderation A simple Moderation System for Laravel 5.* that allows you to Approve or Reject resources like posts, comments, users, etc. Keep yo

Alex Kyriakidis 490 Jun 9, 2021
A laravel Livewire Dynamic Selects with multiple selects depending on each other values, with infinite levels and totally configurable.

Livewire Combobox: A dynamic selects for Laravel Livewire A Laravel Livewire multiple selects depending on each other values, with infinite levels of

Damián Aguilar 15 Jun 5, 2021
Captcha for Laravel 5/6/7/8

Captcha for Laravel 5/6/7 A simple Laravel 5/6 service provider for including the Captcha for Laravel. for Laravel 4 Captcha for Laravel Laravel 4 Pre

MeWebStudio - Muharrem ERİN 1.9k Jun 15, 2021
Phone number functionality for Laravel

Laravel Phone Adds phone number functionality to Laravel and Lumen based on the PHP port of Google's libphonenumber API by giggsey. Table of Contents

null 1.7k Jun 12, 2021
Sortable behaviour for Eloquent models

Sortable behaviour for Eloquent models This package provides a trait that adds sortable behaviour to an Eloquent model. The value of the order column

Spatie 947 Jun 11, 2021