Skip to content

Add schema validation before saving. #3382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

florianJacques
Copy link
Contributor

@florianJacques florianJacques commented May 15, 2025

I suggest introducing an automatic schema validation mechanism before saving data to the database, inspired by the schema validation system in Mongoose (Node.js).
This validation would be handled at the model or persistence layer using Laravel’s native validation system (Illuminate\Validation\Validator).

Goals
• Prevent invalid or incomplete data from being saved.
• Centralize validation rules close to the model or schema definition.
• Improve maintainability and ensure data integrity.

Example Implementation

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Eloquent\SchemaValidation;

class Planet extends Model
{
    use SchemaValidation;

    public function schemaRules(): array
    {
        return [
            'name' => 'required|string',
            'distance' => 'integer|between:10,65535',
        ];
    }
}
<?php

$planet = \App\Models\Planet::query()->first();
$planet->name = 'Earth';
$planet->withValidation()->save();

Checklist

  • Add tests and ensure they pass

@florianJacques florianJacques requested a review from a team as a code owner May 15, 2025 18:11
@florianJacques florianJacques requested a review from alcaeus May 15, 2025 18:11
@florianJacques florianJacques changed the title [feat] Scheme validator Add schema validation before saving. May 15, 2025
@GromNaN
Copy link
Member

GromNaN commented May 15, 2025

Hello @florianJacques, thanks for bringing this idea.

Does this feature require to be part of the laravel-mongodb package, or is it something that could be provided by a third party package? On a quick search, I found watson/validating that is quite popular and seems to be very similar to what you describe.

@florianJacques
Copy link
Contributor Author

Indeed, I didn't know this package. Thank you for taking the time to look at my proposal.

@GromNaN GromNaN requested review from GromNaN and removed request for alcaeus May 15, 2025 19:55
@GromNaN
Copy link
Member

GromNaN commented May 16, 2025

Let me know if you have any compatibility issue with MongoDB.

@florianJacques florianJacques deleted the feat.schema-validation branch May 16, 2025 06:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants