Download the PHP package codezero/laravel-localized-routes without Composer

On this page you can find all versions of the php package codezero/laravel-localized-routes. 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 laravel-localized-routes

Laravel Localized Routes

GitHub release Laravel Build Status Code Coverage Code Quality Total Downloads

ko-fi

A convenient way to set up and use localized routes in a Laravel app.

📖 Table of Contents

✅ Requirements

⬆ Upgrade

Upgrading to a new major version? Check our upgrade guide for instructions.

📦 Install

Install this package with Composer:

Laravel will automatically register the ServiceProvider.

⚙ Configure

☑ Publish Configuration File

You will now find a localized-routes.php file in the config folder.

☑ Configure Supported Locales

Simple Locales

Add any locales you wish to support to your published config/localized-routes.php file:

These locales will be used as a slug, prepended to the URL of your localized routes.

Custom Slugs

You can also use a custom slug for a locale:

Custom Domains

Or you can use a custom domain for a locale:

☑ Use Fallback Locale

When using the route() helper to generate a URL for a locale that is not supported, a Symfony\Component\Routing\Exception\RouteNotFoundException is thrown by Laravel. However, you can configure a fallback locale to attempt to resolve a fallback URL instead. If that fails too, the exception is thrown.

☑ Omit Slug for Main Locale

Specify your main locale if you want to omit its slug from the URL:

This option has no effect if you use domains instead of slugs.

☑ Scoped Options

To set an option for one localized route group only, you can specify it as the second parameter of the localized route macro. This will override the config file settings. Currently, only 2 options can be overridden.

🧩 Add Middleware to Update App Locale

By default, the app locale will always be what you configured in config/app.php. To automatically update the app locale, you need to register the middleware in the web middleware group. Make sure to add it after StartSession and before SubstituteBindings.

The order of the middleware is important if you are using localized route keys (translated slugs)! The session needs to be active when setting the locale, and the locale needs to be set when substituting the route bindings.

Laravel 11 and newer:

Add the middleware to the web middleware group in bootstrap/app.php.

Laravel 10:

Add the middleware to the web middleware group in app/Http/Kernel.php.

Detectors

The middleware runs the following detectors in sequence, until one returns a supported locale:

# Detector Description
1. RouteActionDetector Required. The locales of a localized route is saved in a route action.
2. UrlDetector Required. Tries to find a locale based on the URL slugs or domain.
3. OmittedLocaleDetector Required if an omitted locale is configured. This will always be used.
4. UserDetector Checks a configurable locale attribute on the authenticated user.
5. SessionDetector Checks the session for a previously stored locale.
6. CookieDetector Checks a cookie for a previously stored locale.
7. BrowserDetector Checks the preferred language settings of the visitor's browser.
8. AppDetector Required. Checks the default app locale as a last resort.

Update the detectors array in the config file to choose which detectors to run and in what order.

You can create your own detector by implementing the CodeZero\LocalizedRoutes\Middleware\Detectors\Detector interface and add a reference to it in the config file. The detectors are resolved from Laravel's IOC container, so you can add any dependencies to your constructor.

Stores

If a supported locale is detected, it will automatically be stored in:

# Store Description
1. SessionStore Stores the locale in the session.
2. CookieStore Stores the locale in a cookie.
3. AppStore Required. Sets the locale as the active app locale.

Update the stores array in the config to choose which stores to use.

You can create your own store by implementing the CodeZero\LocalizedRoutes\Middleware\Stores\Store interface and add a reference to it in the config file. The stores are resolved from Laravel's IOC container, so you can add any dependencies to your constructor.

Although no further configuration is needed, you can change advanced settings in the config file.

🚘 Register Routes

Define your routes inside the Route::localized() closure, to automatically register them for each locale.

This will prepend the locale to the route's URI and name. If you configured custom domains, it will use those instead of the URI slugs. You can also use route groups inside the closure.

With supported locales ['en', 'nl'], the above would register:

URI Name
/en/about en.about
/nl/about nl.about

And with the omitted locale set to en, the result would be:

URI Name
/about en.about
/nl/about nl.about

In a most practical scenario, you would register a route either localized or non-localized, but not both. If you do, you will always need to specify a locale to generate the URL with the route() helper, because existing route names always have priority. Especially when omitting a main locale from the URL, this would be problematic, because you can't have, for example, a localized /about route and a non-localized /about route in this case. The same idea applies to the / (root) route! Also note that the route names still have the locale prefix even if the slug is omitted.

☑ Translate Parameters with Route Model Binding

When resolving incoming route parameters from a request, you probably rely on Laravel's route model binding. You typehint a model in the controller, and it will look for a {model} by its ID, or by a specific attribute like {model:slug}. If it finds one that matches the parameter value in the URL, it is injected in the controller.

However, to resolve a localized parameter you need to add a resolveRouteBinding() method to your model. In this method you need to write the logic required to find a match, using the parameter value from the URL.

For example, you might have a JSON column in your database containing translated slugs:

If you are looking for a good solution to implement translated attributes on your models, be sure to check out spatie/laravel-translatable.

☑ Translate Hard-Coded URI Slugs

This package includes codezero/laravel-uri-translator. This registers a Lang::uri() macro that enables you to translate individual, hard-coded URI slugs. Route parameters will not be translated by this macro.

Routes with translated URIs need to have a name in order to generate localized versions of it using the route() helper or the Route::localizedUrl() macro. Because these routes have different slugs depending on the locale, the route name is the only thing that links them together.

First, you create a routes.php translation file in your app's lang folder for each locale, for example:

Then you add the appropriate translations to each file:

And finally, you use the macro when registering routes:

The URI macro accepts 2 additional parameters:

  1. A locale, in case you need translations to a locale other than the current app locale.
  2. A namespace, in case your translation files reside in a package.

You can also use trans()->uri('hello/world') instead of Lang::uri('hello/world').

Example

Using these example translations:

These are possible translation results:

🔦 Localize 404 Pages

A standard 404 response has no actual Route and does not go through the middleware. This means our middleware will not be able to update the locale and the request can not be localized.

To fix this, you can register this fallback route at the end of your routes/web.php file:

Because the fallback route is an actual Route, the middleware will run and update the locale.

The fallback route is a "catch all" route that Laravel provides. If you type in a URL that doesn't exist, this route will be triggered instead of a typical 404 exception.

The FallbackController will attempt to respond with a 404 error view, located at resources/views/errors/404.blade.php. If this view does not exist, the normal Symfony\Component\HttpKernel\Exception\NotFoundHttpException will be thrown. You can configure which view to use by changing the 404_view entry in the config file.

Fallback routes will not apply when:

🗄 Cache Routes

In production, you can safely cache your routes per usual.

⚓ Generate Route URLs

☑ Generate URLs for the Active Locale

You can get the URL of your named routes as usual, using the route() helper.

If you registered an about route that is not localized, then about is an existing route name and its URL will be returned. Otherwise, this will try to generate the about URL for the active locale, e.g. en.about.

☑ Generate URLs for a Specific Locale

In some cases, you might need to generate a URL for a specific locale. For this purpose, an additional locale parameter was added to Laravel's route() helper.

☑ Generate URLs with Localized Parameters

There are a number of ways to generate route URLs with localized parameters.

Pass Localized Parameters Manually

Let's say we have a Post model with a getSlug() method:

Of course, in a real project the slugs wouldn't be hard-coded. If you are looking for a good solution to implement translated attributes on your models, be sure to check out spatie/laravel-translatable.

Now you can pass a localized slug to the route() function:

Use a Custom Localized Route Key

You can let Laravel resolve localized parameters automatically by adding the getRouteKey() method to your model:

Now you can just pass the model:

☑ Fallback URLs

A fallback locale can be provided in the config file. If the locale parameter for the route() helper is not a supported locale, the fallback locale will be used instead.

If neither a regular nor a localized route can be resolved, a Symfony\Component\Routing\Exception\RouteNotFoundException will be thrown.

☑ Generate Localized Versions of the Current URL

To generate a URL for the current route in any locale, you can use the Route::localizedUrl() macro.

Pass Parameters Manually

Just like with the route() helper, you can pass parameters as a second argument.

Let's say we have a Post model with a getSlug() method:

Now you can pass a localized slug to the macro:

Use a Custom Route Key

If you add the model's getRouteKey() method, you don't need to pass the parameter at all.

The macro will now automatically figure out what parameters the current route has and fetch the values.

Multiple Route Keys

If you have a route with multiple keys, like /en/posts/{id}/{slug}, then you can implement the ProvidesRouteParameters interface in your model. From the getRouteParameters() method, you then return the required parameter values.

Now, the parameters will still be resolved automatically:

Keep or Remove Query String

By default, the query string will be included in the generated URL. If you don't want this, you can pass an extra parameter to the macro:

☑ Example Locale Switcher

The following Blade snippet will add a link to the current page in every alternative locale.

It will only run if the current route is localized or a fallback route.

🖋 Generate Signed Route URLs

Generating a localized signed route and temporary signed route URL is just as easy as generating normal route URLs. Pass it the route name, the necessary parameters, and you will get the URL for the current locale.

You can also generate a signed route URL for a specific locale:

Check out the Laravel docs for more info on signed routes.

🚌 Redirect to Routes

You can redirect to routes, just like you would in a normal Laravel app, using the redirect() helper or the Redirect facade.

If you register an about route that is not localized, then about is an existing route name and its URL will be redirected to. Otherwise, this will try to redirect to the about route for the active locale, e.g. en.about:

You can also redirect to URLs in a specific locale:

A localized version of the signedRoute and temporarySignedRoute redirects are included as well:

🪧 Automatically Redirect to Localized URLs

To redirect any non-localized URL to its localized version, you can set the config option redirect_to_localized_urls to true, and register the following fallback route with the FallbackController at the end of your routes/web.php file.

The fallback route is a "catch all" route that Laravel provides. If you type in a URL that doesn't exist, this route will be triggered instead of a typical 404 exception.

The FallbackController will attempt to redirect to a localized version of the URL, or return a localized 404 response if it doesn't exist.

For example:

URI Redirects To
/ /en
/about /en/about

If the omitted locale is set to en:

URI Redirects To
/en /
/en/about /about

If a route doesn't exist, a 404 response will be returned.

🪜 Helpers

Route::hasLocalized()

Route::isLocalized()

Route::isFallback()

🚧 Testing

☕ Credits

🔒 Security

If you discover any security related issues, please e-mail me instead of using the issue tracker.

📑 Changelog

A complete list of all notable changes to this package can be found on the releases page.

📜 License

The MIT License (MIT). Please see License File for more information.


All versions of laravel-localized-routes with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1
codezero/browser-locale Version ^3.0
codezero/composer-preload-files Version ^1.0
codezero/laravel-uri-translator Version ^2.0
codezero/php-url-builder Version ^1.0
illuminate/support Version ^10.0|^11.0
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 codezero/laravel-localized-routes contains the following files

Loading the files please wait ....