Learn how to use Laravel validation to ensure data integrity. Discover how to apply rules, handle failures, and display error messages in your Blade views.
Previously in this course, we learned how to capture user input from forms. While retrieving data is the first step, trusting that data is a recipe for disaster. In this lesson, we’ll move from simply accepting input to verifying it using Laravel’s built-in validation system.
In a production application, you never trust user input. If your Task Manager app expects a task title, what happens if a user submits an empty string or a script tag? Without validation, you’d save garbage data to your database, potentially breaking your UI or exposing your application to security risks.
Laravel makes validation incredibly simple by providing a fluent, expressive interface. Instead of writing complex if/else statements, you define a set of rules, and Laravel handles the rest.
To validate a request, you use the $request->validate() method within your controller. This method accepts an array of rules where the key corresponds to the input field name.
Let's update our TasksController to ensure the title field is present and has a minimum length. Open app/Http/Controllers/TasksController.php and update your store method:
PHPpublic function store(Request $request) { $validatedData = $request->validate([ 'title' => 'required|max:255', 'description' => 'nullable|string', ]); #6A9955">// If validation passes, execution continues here Task::create($validatedData); return redirect('/tasks'); }
In this example:
required: The field must be present and not empty.max:255: The field cannot exceed 255 characters.nullable: The field is optional, but if provided, it must be a string.What happens if the user submits an empty form? Laravel automatically detects that the validation failed. It stops the execution of your controller method and redirects the user back to their previous location.
Crucially, it also flashes the validation errors and the old input data into the session. This means you don't have to manually redirect or carry over the user's input—Laravel handles this infrastructure for you.
Now that the errors are in the session, we need to show them to the user. Laravel makes this easy with the $errors variable, which is automatically available in all your Blade views.
Open the view file where your form lives (e.g., resources/views/tasks/create.blade.php) and add the following code above your form:
BLADE@if ($errors->any()) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form action="/tasks" method="POST"> @csrf <input type="text" name="title" value="{{ old('title') }}"> @error('title') <div class="text-red-500">{{ $message }}</div> @enderror <button type="submit">Create Task</button> </form>
Key concepts used here:
$errors->any(): Checks if there are any validation errors.@foreach ($errors->all()): Iterates through all errors to display them in a list.old('title'): Repopulates the input field with the user's previous input so they don't have to re-type it.@error('title'): A convenient directive to display an error message for a specific field.priority field to your task creation form.TasksController, add a validation rule to ensure the priority field is required and must be an integer.@csrf: If you forget the @csrf directive in your form, your request will fail with a 419 Page Expired error before validation even runs.old(): Users get frustrated when they submit a form, see an error, and find their entire form cleared. Always use the old() helper to maintain a good user experience.Validation is your first line of defense against bad data. By using $request->validate(), you ensure your application only processes clean, expected input. When validation fails, Laravel’s automatic redirect and the global $errors variable allow you to provide instant, helpful feedback to your users, making your application significantly more robust.
Up next: We'll dive into Customizing Validation Error Messages to provide a more polished experience for our users.
Learn to customize Laravel validation error messages to provide clear, helpful feedback to your users. Master field-specific errors and language files.
Read moreLearn how to use Form Requests in Laravel to move validation logic out of your controllers. Keep your code clean, DRY, and professional with this guide.
Introduction to Laravel Validation
Protecting Routes with Middleware
Understanding CSRF Protection
Preventing Mass Assignment
Task Manager: Securing the Application
Introduction to Route Model Binding
Updating Existing Records
Deleting Records
Using Named Routes
Task Manager: Completing CRUD Functionality
Introduction to Database Relationships
Querying Related Data
Handling File Uploads
Using Flash Messages for User Feedback
Task Manager: Adding Status and Priorities
Introduction to Artisan Commands
Debugging with Laravel Tinker
Understanding Service Providers
Using View Composers
Task Manager: Refactoring for Clean Code
Introduction to Testing
Testing Forms and Validation
Using Database Transactions
Handling Global Exceptions
Preparing for Production
Environment Security Best Practices
Managing Assets in Production
Task Manager: Deployment Preparation