What's the best approach for data validation between forms and models on Laravel 5? -
i'm used have model , form validation together, in framework. i'm migrating laravel , trying understand mindset.
what's best approach data validation? i've seen classes out on creating forms , validating requests, isn't unsafe have models saving data without validating before?
how integrate form (frontend), request (backend) , model validation play nicely together? or not done in laravel world @ all?
as starter in laravel myself, can tell mind of learner.
the first thing understand laravel very very very abstract. offers thousands of solutions single problem. since you're starting out, i'm going assume you're using laravel 5 (5.1 more specific).
the $this->validate() controllers
you can use $this->validate() in controllers.
class somecontroller extends controller { public function store(request $request){ $this->validate($request, [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); // passed validation. } }
the validation facade
inside config/app.php
find aliases
field defines validator facade 'validator' => illuminate\support\facades\validator::class
. you can make validators anywhere.
public function store(request $request) { $validator = validator::make($request->all(), [ 'email' => 'required|unique:emails|email', ]); if ($validator->fails()) { // error logic } // store blog post... }
form requests
personally, form requests. allow reuse validation logic defined once in controller feel it. can run in project
php artisan make:request mycustomrequest
that generate new request inside app/http/requests
can write rules inside rules method
. , then, when want use it, type-hint controller method.
here how use it:
public function store(companyrequest $request){ // code executed if rules inside companyrequest // true. }
here file defining companyrequest.
class companyrequest extends request { /** * determine if user authorized make request. * * @return bool */ public function authorize() { return true; } /** * validation rules apply request. * * @return array */ public function rules() { return [ 'name' => 'required|max:255', 'domain' => 'required|max:40' ]; } }
conclusion
there few more ways it. can, instance, use validator::make
facade within eloquent models. laravel offers multiple ways of handling basic problems. have find best , major in it.
Comments
Post a Comment