Skip to content

Commit 440f619

Browse files
committed
- Removed Laravel 5.6 & 6.x & 7.x support
- Added Laravel 9.x support
1 parent a05ee05 commit 440f619

File tree

10 files changed

+179
-107
lines changed

10 files changed

+179
-107
lines changed

README.md

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,12 @@
44
**Manage localized routes and use translatable models in a Laravel app.**
55
- Automatically register the routes for each locale you wish to support.
66
- Optionally remove the locale slug from the URL for your main language.
7-
- Generate localized route URL's using the ``trans_route()`` helper.
7+
- Generate localized route URLs using the `trans_route()` helper.
88
- Allow routes to be cached.
99

1010
## Requirements
11-
- PHP >= 7.1
12-
- Laravel >= 5.6
11+
- PHP >= 7.4
12+
- Laravel >= 7.x
1313

1414
## Installation
1515
You can install this package using Composer.
@@ -22,22 +22,22 @@ composer require sertxudeveloper/laravel-translatable
2222
First you should publish the configuration file.
2323

2424
```sh
25-
php artisan vendor:publish --provider="SertxuDeveloper\Translatable\TranslatableServiceProvider" --tag="config"
25+
php artisan vendor:publish --tag='trans-config'
2626
```
2727

28-
After running this command, you will now find a ``translatable.php`` file in the ``config`` folder.
28+
After running this command, you will now find a `translatable.php`` file in the `config` folder.
2929

30-
### Locales availables
30+
### Locales available
3131
You can set the locales availables in your application. The localized routes will be registered with all of these locales.
3232

3333
```php
34-
"locales" => ["es", "en", "it"],
34+
'locales' => ['es', 'en', 'it'],
3535
```
3636
### Fallback locale
3737
The fallback locale should be the one that not require to be translated.
3838

3939
```php
40-
"fallback_locale" => "es",
40+
'fallback_locale' => 'es',
4141
```
4242
You can also hide the fallback locale from the URL prefix.
4343

@@ -47,20 +47,20 @@ You can also hide the fallback locale from the URL prefix.
4747

4848
# Routes
4949
## Register Routes
50-
All the routes you want lo localize should be registered inside the ``Route::localized`` closure.
50+
All the routes you want lo localize should be registered inside the `Route::localized` closure.
5151

5252
```php
5353
// Not Localized
54-
Route::get('home', HomeController::class.'@index')->name('home');
54+
Route::get('home', [HomeController::class, 'index'])->name('home');
5555

5656
// Localized
5757
Route::localized(function () {
58-
Route::get('blog', BlogController::class.'@index')->name('blog')
59-
Route::get('{slug}', PageController::class.'@index')->name('page')
58+
Route::get('blog', [BlogController::class, 'index'])->name('blog')
59+
Route::get('{slug}', [PageController::class, 'index'])->name('page')
6060
});
6161

6262
// Not Localized
63-
Route::get('about', AboutController::class.'@index')->name('about');
63+
Route::get('about', [AboutController::class, 'index'])->name('about');
6464
```
6565

6666
Inside this closure you can use Route Groups such as Middlewares, Namespaces or even Sub-Domain Routing. This closure will prepend the locale to the route's URI and name.
@@ -86,13 +86,13 @@ This will be the result of the viewed configuration examples.
8686
> Beware that you don't register the same URL twice when omitting the locale. You can't have a localized /about route and also register 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.
8787
8888
## Generate Localized URLs
89-
You should use the ``trans_route`` helper in order to get the requested route localized. To this helper you can pass a route name or a route url, in booth cases it will be localized.
89+
You should use the `trans_route` helper in order to get the requested route localized. To this helper you can pass a route name or a route url, in booth cases it will be localized.
9090

9191
```php
9292
trans_route($name, $parameters = [], $absolute = false, $locale = null)
9393
```
9494

95-
If you pass only the route it will be localized using the current locale (``'en'``).
95+
If you pass only the route it will be localized using the current locale (`'en'`).
9696

9797
```php
9898
trans_route('blog') // /en/blog
@@ -107,7 +107,7 @@ trans_route('page', ['help']) // /en/help
107107
The third param is a boolean to make it absolute or not.
108108

109109
```php
110-
trans_route('page', ['help'], true) // http://your_server_address/en/help
110+
trans_route('page', ['help'], true) // https://yourdomain.test/en/help
111111
```
112112

113113
```php
@@ -121,7 +121,7 @@ trans_route('blog', [], false, 'it') // /it/blog
121121
```
122122

123123
## Switch Locale
124-
If your building a dropdown or similar with links to change the locale of the application, you should use the ``switch_to_locale`` helper.
124+
If you're building a dropdown or similar with links to change the locale of the application, you should use the `switch_to_locale` helper.
125125
```php
126126
switch_to_locale('en') // Changes to 'en' locale without changing the route
127127
```
@@ -132,12 +132,14 @@ switch_to_locale('en') // Changes to 'en' locale without changing the route
132132
You can to customize the name of the translations tables.
133133

134134
```php
135-
"table_sufix" => "_translations"
135+
'table_suffix' => '_translations'
136136
```
137137

138-
The usage of this value will be the following one. If you have the model ``Page`` with the trait ``HasTranslations`` and the model table is ``pages``. This package will lookup for the translations at the table ``page_translations``. Always the model table followed by the table suffix in the config file.
138+
The usage of this value will be the following one. If you have the model `Page` with the trait `HasTranslations` and the model table is `pages`.
139+
This package will look up for the translations at the table `page_translations`. Always the model table followed by the table suffix in the config file.
139140

140-
The translations tables should contain the translatable fields from the model, the id, a column ``locale`` to specify the language saved, ``created_at`` and ``updated_at``. The column ``deleted_at`` should **never** be in the translations table, regardless the models is ``softDeleted`` or not.
141+
The translations tables should contain the translatable fields from the model, the id, a column `locale` to specify the language saved, `created_at` and `updated_at`.
142+
The column `deleted_at` should **never** be in the translations table, regardless the models is `softDeleted` or not.
141143

142144
As you can see in the following example,
143145

@@ -160,10 +162,10 @@ echo $post->getTranslated('name');
160162
```
161163

162164
## Cache Routes
163-
In production you can safely cache your routes per usual.
165+
In production, you can safely cache your routes per usual.
164166

165167
```sh
166168
php artisan route:cache
167169
```
168170
<br><br>
169-
Copyright (c) 2019 Sertxu Developer
171+
Copyright © 2019 Sertxu Developer

composer.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "sertxudeveloper/laravel-translatable",
33
"description": "Manage localized routes and use translatable models in a Laravel app.",
44
"keywords": ["laravel", "translatable", "localization"],
5-
"version": "1.5.0",
5+
"version": "1.6.0",
66
"license": "MIT",
77
"authors": [
88
{
@@ -12,8 +12,8 @@
1212
],
1313
"minimum-stability": "dev",
1414
"require": {
15-
"php": "^7.1|^8.0",
16-
"illuminate/support": "^5.6.0|^6.0|^7.0|^8.0"
15+
"php": "^7.4|^8.0",
16+
"illuminate/support": "^8.0|^9.0"
1717
},
1818
"autoload": {
1919
"psr-4": {

publishable/config/translatable.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,20 @@
55
/**
66
* The locales available in your project.
77
*/
8-
"locales" => ["es", "en", "it"],
8+
'locales' => ['es', 'en', 'it'],
99

1010
/**
1111
* The default locale in your project, it will be used if the requested locale is not available.
1212
*/
13-
"fallback_locale" => "es",
13+
'fallback_locale' => 'en',
1414

1515
/**
1616
* Hide the default locale from the URL.
1717
*/
18-
"hide_fallback_locale" => true,
18+
'hide_fallback_locale' => true,
1919

2020
/**
21-
* The translations table suffix
21+
* The translations' table suffix.
2222
*/
23-
"table_suffix" => "_translations"
23+
'table_suffix' => '_translations'
2424
];

src/Facades/Translatable.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
use Illuminate\Support\Facades\Facade;
66

77
class Translatable extends Facade {
8-
8+
99
/**
1010
* Get the registered name of the component.
11+
*
1112
* @return string
1213
*/
1314
protected static function getFacadeAccessor() {

src/Helpers/helpers.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,20 @@ function switch_to_locale($locale) {
1313
return Translatable::switchToLocale($locale);
1414
}
1515
}
16+
17+
if (!function_exists('is_route')) {
18+
function is_route(string $name): bool {
19+
20+
/** Check route without locales */
21+
if (request()->routeIs($name))
22+
return true;
23+
24+
/** Check route with locales */
25+
foreach (config('translatable.locales') as $locale) {
26+
if (request()->routeIs("$locale.$name"))
27+
return true;
28+
}
29+
30+
return false;
31+
}
32+
}

src/Macros/TranslatableRoutesMacro.php

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,52 +2,49 @@
22

33
namespace SertxuDeveloper\Translatable\Macros;
44

5+
use Closure;
56
use Illuminate\Support\Facades\App;
67
use Illuminate\Support\Facades\Route;
7-
use SertxuDeveloper\Translatable\Facades\Translatable;
88
use SertxuDeveloper\Translatable\Middleware\TranslatableRoutesHandler;
9-
use \Closure;
109

1110
class TranslatableRoutesMacro {
1211

1312
/**
1413
* Register the macro.
14+
*
1515
* @return void
1616
*/
17-
public static function register() {
17+
public static function register() {
1818
if (!Route::hasMacro('localized')) {
1919
function registerRoutes($locale, Closure $closure) {
20-
// $currentLocale = Translatable::getLocaleFromRequest();
2120
$fallbackLocale = config('translatable.fallback_locale');
2221
$hideFallbackLocale = config('translatable.hide_fallback_locale');
2322

2423
$attributes = [];
25-
$attributes["middleware"] = [TranslatableRoutesHandler::class];
24+
$attributes['middleware'] = [TranslatableRoutesHandler::class];
2625

27-
$attributes["as"] = "${locale}.";
28-
$attributes["prefix"] = $locale;
26+
$attributes['as'] = "$locale.";
27+
$attributes['prefix'] = $locale;
2928
Route::group($attributes, $closure);
3029

3130
if ($hideFallbackLocale && $locale === $fallbackLocale) {
3231
$attributes = [];
33-
$attributes["middleware"] = [TranslatableRoutesHandler::class];
32+
$attributes['middleware'] = [TranslatableRoutesHandler::class];
3433
Route::group($attributes, $closure);
3534
}
3635
}
37-
36+
3837
Route::macro('localized', function (Closure $closure) {
3938
$locales = config('translatable.locales');
4039
$fallbackLocale = config('translatable.fallback_locale');
4140

4241
foreach ($locales as $locale) {
43-
if($fallbackLocale === $locale) continue;
42+
if ($fallbackLocale === $locale) continue;
4443
registerRoutes($locale, $closure);
4544
}
4645

4746
registerRoutes($fallbackLocale, $closure);
48-
4947
});
5048
}
5149
}
52-
5350
}

src/Middleware/TranslatableRoutesHandler.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,27 +13,33 @@
1313
class TranslatableRoutesHandler {
1414

1515
/**
16-
* Set language for localized route
16+
* Set language for localized route.
17+
*
1718
* @param \Illuminate\Http\Request $request
1819
* @param \Closure $next
1920
* @return mixed
2021
*/
2122
public function handle(Request $request, Closure $next) {
2223
$params = explode('/', $request->getPathInfo());
24+
2325
// Dump the first element (empty string) as getPathInfo() always returns a leading slash
2426
array_shift($params);
2527

26-
if (\count($params) > 0) {
28+
if (count($params) > 0) {
2729
$locale = $params[0];
30+
2831
if (Translatable::checkLocaleInSupportedLocales($locale)) {
2932
App::setLocale($locale);
33+
3034
if (Translatable::isFallbackLocaleHidden() && Translatable::isFallbackLocale($locale)) {
3135
array_shift($params);
3236
$params = implode('/', $params);
33-
$url = $request->root() . "/${params}";
37+
$url = $request->root() . "/$params";
3438
$query = http_build_query($request->all());
3539
$url = ($query) ? "$url?$query" : $url;
40+
3641
Session::reflash();
42+
3743
return new RedirectResponse($url, 302, ['Vary' => 'Accept-Language']);
3844
}
3945
}

src/Traits/HasTranslations.php

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,23 @@ trait HasTranslations {
1010
/**
1111
* Get the translated $attribute if not exist return the fallback translation
1212
*
13-
* @param $attribute
14-
* @param bool $lang
13+
* @param string $attribute
14+
* @param string|null $lang
1515
* @return string
1616
*/
17-
public function getTranslated($attribute, $lang = false) {
18-
if(!$lang) $lang = App::getLocale();
19-
if (config('translatable.fallback_locale') === $lang) {
17+
public function getTranslated(string $attribute, ?string $lang = null): string {
18+
if (!$lang) $lang = App::getLocale();
19+
20+
if (config('translatable.fallback_locale') === $lang)
2021
return $this[$attribute];
21-
} else {
22-
$translation = DB::table($this->table . config('translatable.table_suffix'))->where([['locale', $lang], [$this->getKeyName(), $this->getKey()]])->first();
2322

24-
return (!isset($translation->$attribute)) ? $this[$attribute] : $translation->$attribute;
25-
}
26-
}
23+
$translation = DB::table($this->table . config('translatable.table_suffix'))
24+
->where([
25+
['locale', $lang], [
26+
$this->getKeyName(), $this->getKey(),
27+
],
28+
])->first();
2729

30+
return (!isset($translation->$attribute)) ? $this[$attribute] : $translation->$attribute;
31+
}
2832
}

0 commit comments

Comments
 (0)