Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Geojson Rule Laravel Package

yucadoo/laravel-geojson-rule

A Laravel validation rule for GeoJSON. Validate geometries, features, and feature collections in form requests or validators, helping ensure map data and spatial payloads are well-formed before storage or processing.

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package with Composer:

composer require yucadoo/laravel-geojson-rule

Laravel package discovery should register the service provider automatically. There is typically no publish step required for basic use; check the README for any optional config or custom validation messages.

Start with the rule class shipped by the package. The exact namespace can vary by version, so confirm it in the installed README; a typical usage looks like:

use Yucadoo\GeoJsonRule\Rules\GeoJson;

$validated = $request->validate([
    'location' => ['required', new GeoJson()],
]);

The first practical use case is an endpoint that receives a map payload from a front-end editor and must reject malformed GeoJSON before storing it:

$validated = $request->validate([
    'name' => ['required', 'string', 'max:255'],
    'geometry' => ['required', new GeoJson()],
]);

Model::create([
    'name' => $validated['name'],
    'geometry' => $validated['geometry'],
]);

The 2.0.7 release is a Laravel 13.x compatibility release. There are no new validation features described in the release notes, so existing 2.0.x usage should remain the reference point.

Implementation Patterns

Use it inside FormRequests for non-trivial endpoints. This keeps controllers clean and lets you combine GeoJSON validation with authorization and domain checks:

class StoreLocationRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Location::class);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'geometry' => ['required', new GeoJson()],
        ];
    }
}

Normalize the incoming payload before validation if clients send JSON strings. Some map libraries send geometry as a string; others send it as an object. Pick one contract and enforce it. If your API accepts the raw string form, decode it in prepareForValidation() or validate a decoded field so the rule receives the shape it expects.

protected function prepareForValidation(): void
{
    if (is_string($this->geometry)) {
        $this->merge([
            'geometry' => json_decode($this->geometry, true),
        ]);
    }
}

Combine GeoJSON validation with business rules. The package answers “is this structurally valid GeoJSON?” It does not replace checks such as allowed geometry types, coordinate bounds, polygon area limits, or tenant-specific restrictions. Pair it with custom rules or closures:

'geometry' => [
    'required',
    new GeoJson(),
    function ($attribute, $value, $fail) {
        if (($value['type'] ?? null) !== 'Polygon') {
            $fail('Only polygon geometries are accepted.');
        }
    },
],

Store as JSON and cast on the model. Keep the payload as an array/object rather than a string so Laravel’s JSON casting and API resources can serialize it naturally:

protected $casts = [
    'geometry' => 'array',
];

Validate once at the boundary, then trust the normalized value downstream. Avoid repeatedly decoding and re-validating the same payload in services, jobs, and observers. Persist the validated structure and pass the model attribute around.

Use it in API and map-editor flows. A common workflow is: map editor submits a Feature or Geometry; the FormRequest validates it; the controller stores it in a json column; an API resource returns it as a JSON object; the front-end renders it. Keep the GeoJSON type and coordinate structure consistent across those steps.

Gotchas and Tips

  • Coordinate order is longitude, latitude. GeoJSON uses [longitude, latitude], not [latitude, longitude]. This is the most common source of “valid but wrong” map data; the rule validates structure, not whether the point appears where the user intended.
  • Structural validity is not semantic validity. A Polygon can be valid GeoJSON while self-intersecting, outside allowed bounds, or inconsistent with your business rules. Add domain checks where needed.
  • Watch JSON string versus array input. Laravel validation and database JSON casts behave differently depending on whether the request contains an object or a serialized string. Decide on one API contract and normalize early.
  • Large FeatureCollections can be expensive to validate. If you accept many features or large polygons, enforce request-size limits and validate after authentication/authorization to avoid unnecessary work on unauthenticated requests.
  • Test empty and edge-case geometries explicitly. Payloads with empty coordinate arrays, FeatureCollection wrappers, holes in polygons, and nullable geometry fields are common edge cases. Include them in feature tests with assertJsonValidationErrors().
  • Use nullable deliberately. If a location is optional, use ['nullable', new GeoJson()]; otherwise a missing field will fail before the GeoJSON rule runs.
  • Check the exact rule namespace against the installed version. The package’s README is the source of truth for imports and any available rule options.
  • Laravel 13 upgrade note: 2.0.7 adds Laravel 13.x compatibility. If you are already on 2.0.6 and not yet on Laravel 13, this is a low-risk compatibility release; still run your validation feature tests after upgrading, especially if you pin framework or package constraints.
  • Debug with small payloads first. When a rule fails unexpectedly, test a minimal Point payload directly through Validator::make() before testing a full FeatureCollection. This quickly separates malformed GeoJSON from unrelated request-validation issues.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource