Download the PHP package teksite/extralaravel without Composer
On this page you can find all versions of the php package teksite/extralaravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download teksite/extralaravel
More information about teksite/extralaravel
Files in teksite/extralaravel
Package extralaravel
Short Description this package add some features such as rules, middlewares, functions to laravel
License MIT
Informations about the package extralaravel
ExtraLaravel
A collection of reusable utilities for Laravel applications: Eloquent casts, validation rules, an API form request, traits, route macros, Artisan generators and maintenance commands, a honeypot middleware, a recursive Blade directive, ready-to-use enums and global helper functions.
ExtraLaravel focuses on small, independent building blocks. Nothing is forced on your application: every piece can be used on its own, and the package does not impose an architecture.
Table of contents
- Requirements
- Installation
- Configuration
- Eloquent casts
- Enums
- Validation rules
- API form request
- Phone verification trait
- Trash (soft delete) management
- Trash resource routes
- Artisan commands
- Honeypot
- Blade directives
- Helper functions
- Translations
- Octane and performance notes
- Upgrade notes
- Testing
- Security notes
- Contributing
- License
- Author
Requirements
| Requirement | Version |
|---|---|
| PHP | 8.3 or newer |
| Laravel | 12.x or 13.x |
morilog/jalali |
^3.5 (installed automatically, used by JalaliDateCast) |
laravel/sanctum |
Optional. Only needed for the expired-token step of cache:purge. |
The test suite runs on PHP 8.3 and 8.4 against Laravel 12 and 13 (Orchestra Testbench 10 and 11).
Installation
The service provider is registered through Laravel's package auto-discovery, so no manual step is required.
If your application disables package discovery, register it yourself in bootstrap/providers.php:
The global helper functions (changeToSlug(), getStaticData(), ...) are loaded automatically through Composer's
autoload.files.
Configuration
The package works without publishing anything: its defaults are merged into your configuration automatically. To customize them, publish the config file:
Available publish tags:
| Tag | What it publishes |
|---|---|
extralaravel |
Everything below |
extralaravel-config |
config/extralaravel.php |
extralaravel-stubs |
Generator stubs to stubs/extralaravel/ |
The default configuration:
Eloquent casts
IpCast
Stores an IP address and validates it.
- When the attribute is set to
null, the IP of the current request (request()->ip()) is stored. - Any other value must be a valid IPv4 or IPv6 address, otherwise an
InvalidArgumentExceptionis thrown. Arbitrary text is never stored.
JalaliDateCast
Converts between the Gregorian calendar (stored in the database) and the Jalali calendar (shown to users),
using morilog/jalali.
The conversion is active only when the application locale is listed in extralaravel.jalali_date_locales
(['fa'] by default). In every other locale the value passes through unchanged.
Details:
- On write, only strings that look like a Jalali date (
YYYY/MM/DDorYYYY-MM-DD, optionalHH:MM[:SS], year below 1700) are converted. Other strings andDateTimeInterfaceinstances are stored as they are. - An impossible Jalali date throws an
InvalidArgumentException. - Setting the attribute to
nullstores the current time (now()), notNULL. Do not use this cast on nullable columns whereNULLmust be preserved.
SlugCast
Turns a string into a URL-friendly slug when the attribute is set.
Persian text is kept intact. The same logic is available as the changeToSlug() helper.
Enums
All enums live in Teksite\Extralaravel\Enums.
| Enum | Cases | Backed value | Example |
|---|---|---|---|
Areas |
252 | country name | Areas::IR->value is "Iran" |
Currencies |
168 | currency name | Currencies::USD->value is "US Dollar" |
Langs |
142 | language name | Langs::fa->value is "Persian - فارسی" |
LocalLangs |
434 | locale name | LocalLangs::fa_IR->value is "Persian (Iran)" |
Educations |
6 | degree name | Educations::BACHELOR->value is "bachelor's degree" |
TimeZones |
400 | (not backed) | TimeZones::Asia_Tehran |
MobilePatterns |
88 | (not backed) | MobilePatterns::IRAN |
The backed enums are regular PHP enums, so from(), tryFrom() and cases() work as usual:
TimeZones
Static offset table for every supported zone. Case names use underscores instead of slashes
(Asia_Tehran is Asia/Tehran).
MobilePatterns
Mobile number rules for 88 countries. It powers MobileRule, but is also useful on its own. Patterns for the first
ten countries (Iran, USA, Canada, United Kingdom, Germany, France, Turkey, UAE, India, Australia) are
intentionally lenient; the other patterns are derived from Google's
libphonenumber mobile ranges. Treat a match as "looks like a mobile
number of this country", not as proof that the number is assigned to a subscriber.
Accepted input formats (after normalization): the number with an international prefix (+989123456789,
00989123456789), with the national trunk prefix (09123456789) or without any prefix (9123456789).
Persian/Arabic digits, spaces and punctuation are handled automatically. A bare digit string that starts with the
dial code but has no + or 00 (for example 989123456789) is not accepted.
Instance methods
| Method | Description |
|---|---|
code() |
Dial code without + ("98"). USA/Canada share "1", Russia/Kazakhstan "7". |
iso() |
ISO 3166-1 alpha-2 code ("IR"). |
label() |
English country name. |
flag() |
Flag emoji. Some platforms (e.g. Windows) render the two letters instead. |
nationalPrefix() |
Trunk prefix ("0", "8", "06") or "" when the country has none. |
pattern() |
The regular expression. |
example($international) |
A valid sample number, national (09123456789) or international (+98...). |
validate($phone) |
Normalizes the input, then tests it. |
matches($normalizedPhone) |
Tests an already normalized number (normalize once when checking many countries). |
nationalNumber($phone) |
Number without international or trunk prefix, or null when invalid. |
toNational($phone) |
Trunk prefix + national number ("09123456789"), or null. |
toE164($phone) |
"+989123456789", or null. |
Static methods
| Method | Description |
|---|---|
normalize($phone) |
Digits to English, everything except digits and + removed, 00 becomes +. |
country($name) |
Find by case name, English label, ISO code or the UK alias. Returns null if unknown. |
fromIso($iso) |
Find by ISO code ("ir", "GB", "UK"). |
fromDialCode($code) |
List of countries using a dial code ("98", "+98", "0098", 98). |
validateWithCountry($phone, $country) |
Validate against one country (enum or name). |
validateAny($phone, $countries = null) |
Validate against several countries, or against all of them. |
detectCountry($phone) |
First matching country in declaration order. |
detectCountries($phone) |
Every matching country. |
canonical($phone, $country = null) |
Digits-only international form ("989123456789"). |
e164($phone, $country = null) |
Same with a leading +. |
areSame($a, $b, $country = null) |
Whether two numbers are the same subscriber, however written. |
options($sortByLabel = false) |
['IR' => 'Iran', ...] for select boxes. |
mask($phone, $visibleStart = 4, $visibleEnd = 3) |
Hide the middle of a number for logs: +989******789. |
Notes:
- Numbers without any prefix can match several countries. Use
+numbers (or pass the country explicitly) when you need a reliable result.detectCountry()returns the first match in declaration order, which is why the first ten cases keep their original order. - Inputs longer than 20 characters after normalization are rejected before any regular expression runs.
- Mobile ranges change over time; refresh the patterns from libphonenumber periodically.
Validation rules
All rules implement Laravel's ValidationRule contract and can be used in arrays, Rule lists and FormRequests.
Failure messages are translatable, see Translations.
CodeMeliRule
Validates an Iranian national code (10 digits and check digit). Persian and Arabic digits are accepted, integers are
left-padded with zeros, and codes made of a single repeated digit (1111111111) are rejected.
MobileRule
Country-specific mobile validation built on MobilePatterns. Iran is the default.
- An unknown country name throws
InvalidArgumentExceptionwhen the rule is constructed. - Input that is not a string, is empty, or is longer than 32 characters fails immediately and is never normalized.
- To customize the generic failure message, define the
validation.mobiletranslation key in your application.
PasswordRule
Requires a lowercase letter, an uppercase letter, a number and a symbol, within a length range. Every failed requirement is reported separately. Any character that is neither a letter nor a digit (in any script) counts as a symbol, so Persian letters are not symbols.
The maximum length protects your hasher from extremely long inputs.
NoHtmlRule
Fails when the value contains HTML tags (strip_tags($value) !== $value). Non-string values are ignored.
This is input validation, not XSS protection. Always escape output.
NeverPassRule
Always fails. Useful for disabling a field temporarily or for testing validation flows.
API form request
ApiFormRequest returns validation and authorization failures as JSON instead of redirecting or rendering HTML.
Validation failure (HTTP 422):
Authorization failure (HTTP 403):
Generate a request class with make:request-api.
Phone verification trait
MustVerifyPhone mirrors Laravel's email verification helpers for phone numbers.
The model needs the phone and phone_verified_at columns.
| Method | Description |
|---|---|
hasVerifiedPhone(): bool |
true when phone_verified_at is not null. |
markPhoneAsVerified(): bool |
Sets phone_verified_at to now and saves. |
markPhoneAsUnverified(): bool |
Clears phone_verified_at and saves. |
getPhoneForVerification(): string |
Returns $this->phone as a string. |
sendPhoneVerificationNotification() |
Abstract. You implement it. |
Trash (soft delete) management
TrashMethods gives a service class a complete API for working with the soft-deleted records of one model. The model
must use Laravel's SoftDeletes trait; otherwise a LogicException is thrown.
| Method | Description |
|---|---|
trashCount(): int |
Number of trashed records. |
getTrashes(...) |
Paginated trashed records (see below). |
restore($ids) / restoreOne($id) |
Restore records. Returns the number of restored records. |
restoreAll() |
Restore everything in the trash. |
wipe($ids) / wipeOne($id) |
Permanently delete (forceDelete) trashed records. |
wipeAll() |
Permanently delete everything in the trash. |
restoreWithEvents($ids), restoreOneWithEvents($id), restoreAllWithEvents() |
Same as above, but record by record so model events fire (restoring, restored). |
wipeWithEvents($ids), wipeOneWithEvents($id), wipeAllWithEvents() |
Same, firing forceDeleting / forceDeleted. |
Behavior worth knowing:
- Only trashed records are ever touched. Passing the ID of an active record changes nothing and is not counted.
nulland empty-string IDs are ignored.- The plain variants (
restore,wipe, ...) run a single bulk query and do not fire model events. Use the*WithEventsvariants when observers or listeners must run; they process records in chunks. - Large ID lists are split into chunks (1000 by default) so they cannot exceed a database driver's bound-parameter limit.
getTrashes()caps the page size at 250 (and never goes below 1), so a client-suppliedper_pagecannot request the whole table. Still validate request input before passing it in.
Override these protected hooks to customize the behavior:
Trash resource routes
Route::trashResource() registers five standard routes for a soft-deletable resource.
| Action | Method | URI | Route name | Controller method |
|---|---|---|---|---|
index |
GET | /users/trash |
users.trash.index |
index() |
reinstate |
PATCH | /users/trash/{user} |
users.trash.reinstate |
reinstate($id) |
prune |
DELETE | /users/trash/{user} |
users.trash.prune |
prune($id) |
restore |
PATCH | /users/trash |
users.trash.restore |
restore() |
flush |
DELETE | /users/trash |
users.trash.flush |
flush() |
The wildcard is the singular form of the resource (users becomes {user}). reinstate and prune load the model
with withTrashed() and are protected by TrashOnlyBindingMiddleware, which answers 404 when:
- the target record is not soft-deleted, or
- a parent record of a nested resource is soft-deleted.
This means PATCH /users/trash/5 can never act on an active user. Model binding must run (the web/api middleware
groups include SubstituteBindings). Scaffold the matching controller with
make:controller-trash.
Nested resources
Options
Pass options as the third argument or chain them fluently. Both produce the same routes.
| Option | Description |
|---|---|
prefix |
URI prefix. |
middleware |
String or array of middleware applied to all generated routes. |
as |
Route name prefix; names are {as}.{resource}.trash.{action}. |
only / except |
Limit the actions. Unknown action names throw InvalidArgumentException; using the same action in both throws too. |
where |
Route parameter constraints, e.g. ['user' => '[0-9]+']. |
parameters |
Rename wildcards, e.g. ['users' => 'account'] gives {account}. |
names |
Custom route name per action, e.g. ['index' => 'trash.list']. |
scoped / scopeBindings |
Scoped route-model binding for nested resources. |
bindingFields |
Custom binding columns, e.g. ['user' => 'uuid']. |
shallow |
Use shallow URIs for single-record actions of nested resources. |
Register several resources at once with Route::trashResources(['users' => UserController::class, ...], $options).
Restrict these routes with authentication and authorization.
pruneandflushdelete data permanently.
Artisan commands
Commands are registered only when the application runs in the console.
API request generator
Creates a class in app/Http/Requests that extends ApiFormRequest.
Logic generator
Creates an empty class in app/Logics, handy for query and business logic that does not belong in a controller or model.
Service generator
Creates a class in app/Services with an execute(): void method.
Trash controller generator
Creates a controller in app/Http/Controllers with the five methods expected by
Route::trashResource().
All generators accept --force (-f) to overwrite an existing class. Without it, an existing class is never
overwritten.
Customizing stubs
Stubs are copied to stubs/extralaravel/. When a file with the same name exists there, it is used instead of the
package stub. Available stubs: api-request.stub, logic-class.stub, service-class.stub,
trash-resource-controller.stub, trash-resource-controller-api.stub. Placeholders: {{ namespace }},
{{ rootNamespace }}, {{ class }}.
cache:purge
Removes expired cache data:
- expired rows of a database cache store, and expired rows of its cache lock table
- expired files of the file cache (empty directories are removed afterwards)
- expired Sanctum tokens (through
sanctum:prune-expired, when Sanctum is installed)
| Option | Description |
|---|---|
--dry-run |
Counts what would be deleted. Nothing is deleted and no confirmation is asked; the Sanctum step is skipped. |
--force |
Run without confirmation in production. |
--limit= |
Records or files processed per batch. |
--store= |
Cache store (from config/cache.php) that must use the database driver. |
--connection= |
Database connection used instead of the store's own connection. |
--skip-database |
Skip the database cache and cache lock tables. |
--skip-files |
Skip the file cache (cache.stores.file.path, default storage/framework/cache/data). |
--skip-tokens |
Skip Sanctum token pruning. |
In production the command asks for confirmation unless --force or --dry-run is given. A summary is printed and,
for real runs, written to the log. It is safe to schedule:
Honeypot
A simple trap for automated form submissions: a hidden field that real users never fill in.
-
Add the field to your form with the Blade directive:
It renders an off-screen text input (not
display:none, which simple bots skip) witharia-hidden,tabindex="-1"andautocomplete="off". Outside Blade useTeksite\Extralaravel\Support\Honeypot::field(). - Protect the route with the
honeypotmiddleware alias:
If the field is present and not empty, the request is aborted with the configured status (403 by default). Set
extralaravel.honeypot.enabled to false to turn the check off. An invalid configured status falls back to 403.
Blade directives
@honeypot
See Honeypot.
@recursive
Runs its body once for every leaf (non-iterable) value found anywhere inside a nested array or collection.
It compiles to a plain foreach, so the body shares the template's variables.
- The expression may contain commas:
@recursive(array_merge($a, $b), $leaf). - A non-iterable value (for example
null) renders nothing. - Nesting deeper than 64 levels (for example a self-referencing object) throws a
LogicException. - The second argument must be a plain variable name; otherwise an
InvalidArgumentExceptionis thrown at compile time.
Helper functions
Global helpers are defined only if a function with the same name does not exist yet.
| Function | Description |
|---|---|
changeToSlug(string $slug, string $separator = '-'): Stringable |
Slug that keeps Persian text and splits camelCase. |
toEnglishNumber(string $value): string |
Persian and Arabic digits to English digits. |
normalizePersianText(?string $string): ?string |
Arabic letter variants to Persian (ي→ی, ك→ک, ...) and strips diacritics. |
convertSeconds(?int $seconds, ?string $format = 'string') |
Seconds to HH:MM:SS or, with 'array', to hours/minutes/seconds. Negative values count as 0. |
currentUrlWithoutQueries(): string |
Current URL without the query string. |
exploding(?string $string): ?Collection |
Split by , and ،, trimming each part. Returns null for null. |
var_export_short(mixed $value, bool $return = false): ?string |
var_export() with [] syntax; prints unless $return is true. |
arrayToDot(string $name): string |
users[0][name] to users.0.name. |
dotToArray(string $name): string |
users.0.name to users[0][name]. |
normalizePath(string $path): string |
Unify and collapse directory separators. Does not resolve .., so it is not a traversal guard. |
is_rtl(?string $language = null): bool |
Whether a locale is right-to-left. Region suffixes are ignored (fa, fa_IR, fa-IR). Uses the app locale by default. |
get_error(MessageBag $errors, string $name): array |
Validation errors for a field written as users[0][email]. |
getStaticData(string $key, mixed $default = null, string $prePath = ''): mixed |
Read values from PHP data files (see below). |
getStaticData()
Reads static data from PHP files inside the configured data directory (extralaravel.data_path, app/data by
default) using dot notation. The key starts with the data directory path, followed by the file path and then the keys
inside the returned array.
Resolution tries the longest-to-shortest file match from the left (app/data/times.php, then
app/data/times/iran.php, ...) and walks the remaining segments through the returned array. Loaded files are cached
per request.
Security: the helper executes the PHP files it resolves. Keys must start with the configured data directory, segments containing
.., slashes or null bytes are rejected, and symlinks that point outside the directory are ignored. Never pointdata_pathat a directory that contains files you would not want executed, and keep it relative tobase_path().
Translations
Rule failure messages are English sentences passed through Laravel's translator, so you translate them with a JSON
language file in your application (for example lang/fa.json). The package does not ship translation files; add the
keys you need:
MobileRule and CodeMeliRule first look for the validation.mobile and validation.invalid_national_code keys in
your own validation.php and use them when they exist. Messages use the attribute display name, so
validation.attributes works as usual.
Octane and performance notes
- The config is merged once; Artisan commands and publishing are registered only in the console.
getStaticData()is backed by a scoped binding (StaticData), so nothing leaks between Octane requests, and failed lookups are remembered for the rest of the request.- Digit conversion, slug normalization and mobile normalization use constant lookup tables and a single pass.
MobilePatterns::detectCountry()skips countries whose dial code cannot match a+number before running any regular expression.- The trash route registrar is a singleton; routes use controller-action arrays, not closures.
Upgrade notes
Behavior that differs from older releases:
- PHP 8.3 or newer and Laravel 12 or 13 are required.
getStaticData()only reads insideextralaravel.data_path. Setdata_pathto the directory that holds your data files and make sure your keys start with it.PasswordRuledefaults are stricter: minimum 8 (was 6), maximum 128, and each failed requirement is a separate error. Usenew PasswordRule(6)orextralaravel.password.min_lengthto restore the old minimum.IpCastthrowsInvalidArgumentExceptionfor values that are not valid IP addresses.@recursive($items, $item)renders leaves at any depth; the old behavior of rendering a view namedrecursiveis gone.RecursiveDirectives::recursive()is deprecated in favor ofRecursiveDirectives::register($blade).TrashOnlyBindingMiddlewareaccepts the target route parameter as its argument (for exampleTrashOnlyBindingMiddleware::class.':post'; the last route parameter is used when omitted) and also rejects trashed parents of nested resources. Routes registered throughtrashResource()configure it automatically.- The Jalali config key is
jalali_date_locales. Older releases used the misspelled keyjalalit_date_locales, which is no longer read: rename it in your publishedconfig/extralaravel.php, otherwise only['fa']is used. - The default
data_pathisapp/data(relative tobase_path()); older releases used/app/data. PasswordRulemessages are now the English sentences listed under Translations. The oldthe password should ...translation keys are no longer used, so update your language files.TimeZones::Canada_East_SaskatchewaandTimeZones::Antarctica_DumontDUrvilwere misspelled and are nowCanada_East_SaskatchewanandAntarctica_DumontDUrville.changeToSlug()andSlugCastsplit camelCase only at word boundaries (HTMLParserbecomeshtml-parser).
Testing
The suite uses PHPUnit with Orchestra Testbench. GitHub Actions runs it on PHP 8.3 and 8.4 against Laravel 12 and 13.
Security notes
ExtraLaravel does not replace Laravel's own security features. In particular:
- Always use Laravel's authorization system for trash routes, especially
pruneandflush. - Escape user-controlled output.
NoHtmlRuleis validation only. - Validate and sanitize file uploads independently.
- Keep
getStaticData()pointed at a directory you control. - Run
cache:purge --dry-runfirst when using it on a new environment. - Keep the honeypot field name unpredictable if you target determined bots.
Please report security issues privately by email instead of opening a public issue.
Contributing
Contributions are welcome. Before opening a pull request:
- Write or update tests.
- Follow PSR-12 and Laravel conventions.
- Run
composer test. - Keep changes focused and backward compatible where possible, and describe any breaking change.
License
This package is open-sourced software licensed under the MIT license.
Author
Developed by Sina Zangiband.
- Websites: teksite.net, laratek.net, laratek.ir
- Email: [email protected]