Laravel form request validation

Updated at 20-Apr-2021, By samar

Laravel form request validation

We’ll attempt to use programming in this lesson to solve the "Laravel form request validation" puzzle.

  • Validate form request using validate method on request

    --PATH app\Http\Controllers\<YourController>.php
    // Use before class definition
    use Illuminate\Http\Request;
    
    // Controller&rsquo;s method
    public function store(Request $request)
    {
    	$request->validate([
    	    'title' => 'required|unique:posts|max:10',
    	    'body' => 'required'
    	]);
    
    	// Validated
    }
    

    This method is used to validate form request using Illuminate\Http\Request object. If the validation fails it returns back to the user with the error response else keep executing the script.

  • Validate form request using Validator Facade

    --PATH app\Http\Controllers\<YourController>.php
    // Use before class definition
    use Illuminate\Support\Facades\Validator;
    
    // Controller's method
    public function store(Request $request)
    {
    	$validator = Validator::make($request->all(), [
    	    'title' => 'required|unique:posts|max:1',
    	    'body' => 'required|max:2',
    	]);
    
    	if($validator->fails()){
    	    return  redirect()->back()->withErrors($validator)->withInput();
    	}
    }
    

    You can create a validator instance manually using the Validator facade. Using this code snippet you can validate form requests manually using the make() method on Validator facade. If you want to know how to display validation errors in view file click here .

Back to code snippet queries related laravel