Laravel form request validation

Answers 2
  • 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
    }
    
    0

    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();
    	}
    }
    
    0

    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