Quantcast
Channel: Laravel News
Viewing all articles
Browse latest Browse all 1788

Generate Validation Rules from a Database Schema in Laravel

$
0
0

Generate Validation Rules from a Database Schema in Laravel


Laravel Schema Rules is a package that automatically generates basic Laravel validation rules based on your database table schema. You can use this package as a starting point to quickly create boilerplate rules and optimize as needed.

Given the following schema (from in the README) for your table:

Schema::create('persons', function (Blueprint $table) {
    $table->id();
    $table->string('first_name', 100);
    $table->string('last_name', 100);
    $table->string('email');
    $table->foreignId('address_id')->constrained();
    $table->text('bio')->nullable();
    $table->enum('gender', ['m', 'f', 'd']);
    $table->date('birth');
    $table->year('graduated');
    $table->float('body_size');
    $table->unsignedTinyInteger('children_count')->nullable();
    $table->integer('account_balance');
    $table->unsignedInteger('net_income');
    $table->boolean('send_newsletter')->nullable();
});

You can run the schema:generate-rules Artisan command to generate validation rules:

$ php artisan schema:generate-rules persons

[
    'first_name' => ['required', 'string', 'min:1', 'max:100'],
    'last_name' => ['required', 'string', 'min:1', 'max:100'],
    'email' => ['required', 'string', 'min:1', 'max:255'],
    'address_id' => ['required', 'exists:addresses,id'],
    'bio' => ['nullable', 'string', 'min:1'],
    'gender' => ['required', 'string', 'in:m,f,d'],
    'birth' => ['required', 'date'],
    'graduated' => ['required', 'integer', 'min:1901', 'max:2155'],
    'body_size' => ['required', 'numeric'],
    'children_count' => ['nullable', 'integer', 'min:0', 'max:255'],
    'account_balance' => ['required', 'integer', 'min:-2147483648', 'max:2147483647'],
    'net_income' => ['required', 'integer', 'min:0', 'max:4294967295'],
    'send_newsletter' => ['nullable', 'boolean']
]

You can also target specific columns, skip columns, and even generate a form request class.

There's also an online version of this package that you can use to experiment with this package or use it to manually take a schema and convert it to an array of validation rules:

Visit validationforlaravel.com to try it out!

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

The post Generate Validation Rules from a Database Schema in Laravel appeared first on Laravel News.

Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.


Viewing all articles
Browse latest Browse all 1788

Trending Articles