- Create a Request Class:
As before, create a request class with your validation rules.
php artisan make:request StoreUserRequest
Define your validation rules in the generated request class (StoreUserRequest):
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
'password' => 'required|string|min:8',
];
}
}
- Validate the Array Data in the Controller:
In your controller, you can validate the array data using the validation rules from the request class and additional rules if needed.
namespace App\Http\Controllers;
use App\Http\Requests\StoreUserRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function store(Request $request)
{
// Example array data (in real use-case, this might come from another source)
$data = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'password' => 'secret1234',
'age' => 25,
'terms' => true,
];
// Retrieve rules from the request class
$requestClass = new StoreUserRequest();
$rulesFromRequestClass = $requestClass->rules();
// Additional validation rules
$additionalRules = [
'age' => 'required|integer|min:18',
'terms' => 'accepted',
];
// Combine rules from the request class and additional rules
$combinedRules = array_merge($rulesFromRequestClass, $additionalRules);
// Validate the data array with the combined rules
$validator = Validator::make($data, $combinedRules);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 422);
}
// Use the validated data for further processing
$validatedData = $validator->validated();
// Example: Create a new user
$user = User::create($validatedData);
return response()->json(['message' => 'User created successfully', 'user' => $user], 201);
}
}
- Customize Validation Messages (Optional):
You can customize the validation messages in the request class as needed.
public function messages()
{
return [
'name.required' => 'The name field is required.',
'email.required' => 'The email field is required.',
'email.email' => 'The email must be a valid email address.',
'password.required' => 'The password field is required.',
'age.required' => 'The age field is required.',
'terms.accepted' => 'You must accept the terms and conditions.',
];
}
By following these steps, you can validate array data using the validation rules defined in a request class, combined with additional rules, in your Laravel controller.
Top comments (0)