LARAVEL

Laravel Validation


Laravel provides a powerful validation system to validate incoming HTTP request data with a variety of powerful rules. Here's how you can perform validation in Laravel.

 

Using Validation Rules in Controllers

 

1.  Validate Method:

In your controller, you can validate incoming request data using the validate method. Typically, this method is called within your controller methods

Example :

use Illuminate\Http\Request;

public function store(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|string|min:8|confirmed',
    ]);

    // If the validation passes, you can proceed with storing data or other actions
}

Here, the validate method receives an array of validation rules. If the validation fails, Laravel will automatically redirect the user back to their previous location with error messages. and it is work only with html FORM not with API as

 

Displaying Validation Errors in Views:

After validating the incoming request, you can display validation error messages in your views. Here's how you can do it.

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

 

2. Manually Creating Validators:

You can also create a validator instance manually for more control over the validation process

Example :

use Illuminate\Support\Facades\Validator;

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users|max:255',
        'password' => 'required|string|min:8|confirmed',
    ]);

    if ($validator->fails()) {
        return redirect('your-form')
                    ->withErrors($validator)
                    ->withInput();
    }

    // If the validation passes, you can proceed with storing data or other actions
}

Here, the Validator::make method receives an array of validation rules. If the validation fails, Laravel will automatically redirect the user back to their previous location with error messages. and it is work only with html FORM and API both.

 

 

 

 


 

 


LARAVEL