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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

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

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.

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:

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:


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.

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:

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:

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. prune and flush delete 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:

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.

  1. Add the field to your form with the Blade directive:

    It renders an off-screen text input (not display:none, which simple bots skip) with aria-hidden, tabindex="-1" and autocomplete="off". Outside Blade use Teksite\Extralaravel\Support\Honeypot::field().

  2. Protect the route with the honeypot middleware 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.


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 point data_path at a directory that contains files you would not want executed, and keep it relative to base_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


Upgrade notes

Behavior that differs from older releases:


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:

Please report security issues privately by email instead of opening a public issue.


Contributing

Contributions are welcome. Before opening a pull request:

  1. Write or update tests.
  2. Follow PSR-12 and Laravel conventions.
  3. Run composer test.
  4. 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.


All versions of extralaravel with dependencies

PHP Build Version
Package Version
Requires php Version ^8.3
laravel/framework Version ^13.0
morilog/jalali Version ^3.5
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package teksite/extralaravel contains the following files

Loading the files please wait ...