3

In laravel 5 I describe models without specifying fields in model class. Some magic identifies which fields exist in database for this model.

use Illuminate\Database\Eloquent\Model;
class MyModel extends Model {}

When I describe migration for model's table, I specify field type, length and so on. This info exists only in my head and in database.

When I need to validate data, I have to specify requirements again.

What I want - describe all requirements for all fields in one place. Like so:

class MyModel extends Model {
 public $form_fields = [
 'email' => ['required', 'email', 'human_name' => 'E-mail', 'input_type' => 'text'],
 'age' => ['required', 'positive_integer', 'range:18,90', 'input_type' => 'text'],
 'first_name' => ['string', 'human_name' => 'Your first name', 'input_type' => 'text'],
 'agreement' => ['required', 'human_name' 
 ];
}

Why I need this?

This way I want to ensure that all rules for all models will be written in one place.

Later I want to take these rules in validation

$this->validate($request, MyModel::$form_fields);

and in templates

{{ show_field(MyModel::$form_fields['email']) }}
{{ show_field(MyModel::$form_fields['age']) }}
{{ show_field(MyModel::$form_fields['first_name']) }}

show_field is some global function which takes 'human_name' and 'input_type' and generates html code with all required validation rules. May be there is some function or class with required functionality exists?

How can I achieve this?

asked Oct 21, 2016 at 7:06

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.