Laravel Easy POST Validation

Submitted by kecsot - 8 years ago

Create your own request! Before your code run in controller the validation was check the all input. When something wrong, its return redirect back with all error. And you can overwrite the default error messages!

// STEP - 1
    Route::post('/product/add/', 'ProductController@addFood');

// STEP - 2
    // Your method in controller
    // $request type is AddFoodRequest (STEP - 3)
    public function addFood(AddFoodRequest $request)
    {
       $newFood = new Food();
       $newFood -> fill($request);
       $newFood -> save();
       return Redirect::back()->withSuccess('Success!');
    }

//STEP - 3
    // Create a request file for post:
    // php artisan make:request AddFoodRequest
    // You found this new file in app/http/Request folder
    namespace App\Http\Requests;
    use App\Http\Requests\Request;
     
    class AddFoodRequest extends Request
    {
        public function rules(){
            return [
                'foodName' => 'required',
                'price' => 'required'
            ];
        }
     
        public function messages() {
            return [
                'foodName.required'=>'Please set the food name!',
                'price.required'=>'Please set the price!',
            ];
        }
     
        public function authorize() {
            return true;
        }
    }