It is recommended to define the specific validation rules for individual endpoints in their separate request classes, which can inherit the base request class. This approach helps to keep the code organized and maintainable.
By creating separate request classes for each endpoint, you can encapsulate the validation logic specific to that endpoint. This allows for better separation of concerns and makes it easier to understand and maintain the code.
Here's an example of how you can implement this approach:
- Create a base request class that contains the reusable business validation logic. This class should extend the Laravel's base request class.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BaseRequest extends FormRequest
{
// Add your reusable business validation logic here
}
- Create a separate request class for each endpoint that needs specific validation rules. These classes should extend the base request class.
namespace App\Http\Requests;
class EndpointRequest extends BaseRequest
{
public function rules()
{
return [
// Define the specific validation rules for this endpoint
];
}
}
- In your controller, type-hint the specific request class for each endpoint.
namespace App\Http\Controllers;
use App\Http\Requests\EndpointRequest;
class EndpointController extends Controller
{
public function store(EndpointRequest $request)
{
// The request will automatically be validated based on the rules defined in EndpointRequest
// Your controller logic goes here
}
}
By following this approach, you can easily manage and reuse your validation logic across different endpoints while keeping the codebase clean and maintainable.