2 years ago

validation rules abstraction

Posted 2 years ago by jahstation

Hi to all, I've a silly question for some expert that drive me crazy and maybe is so simple to solve: validation how to make it aviable for any method on a controller.

If i write a store method inside a controller and i put some validation everything works perfect:

public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:255', 'business_name' => 'required', 'address' => 'required', 'email' => 'required|email|max:255', 'phone' => 'required|alpha_num', 'vat_number' => 'required|regex:/^[0-9]{11}$/', ]); ..... }

but I'd like to have these rules aviable for any method thats need validation, for example for the update method. And even try to personalize some message; So I add 2 protected variables in my controller called "$rules" and "$message" then ive included the "use Illuminate\Support\Facades\Validator;"

so is like: protected static $messages = [ 'required' => 'The :attribute field is required.', ];

protected static $rules= [
    'name' => 'required|max:255',
    'business_name' => 'required',
    'address' => 'required',
    'email' => 'required|email|max:255',
    'phone' => 'required|alpha_num',
    'vat_number' => 'required|regex:/^[0-9]{11}$/',

Then on the method I try to call something like:

public function store(Request $request){

$validator = Validator::make($request, $rules, $messages);

But from that point: 1- the variable rules/message are not aviable, why? 2- is it the correct abstraction? 3- if the Validator::make fail then how the errors are sended back to frontend? do i need to explict it or the old code that using $errors on blade template is still working?

Please sign in or create an account to participate in this conversation.