Giter VIP home page Giter VIP logo

localization's Introduction

Localization Packagist License For Laravel

Github Workflow Status Coverage Status Scrutinizer Code Quality SensioLabs Insight Github Issues

Packagist Packagist Release Packagist Downloads

By ARCANEDEV©

Easy i18n localization for Laravel, a useful tool to combine with Laravel localization classes.

Official documentation for Localization package can be found at the Docs folder.

Feel free to check out the releases, license, and contribution guidelines.

Features

  • Easy setup & configuration.
  • Laravel 5.x to 9.x are supported.
  • SEO-Friendly (Search engine optimization).
  • New extended Router to manage your localized routes.
  • Translated Eloquent Models.
  • Locales selector menu (Publishable & Customizable).
  • Locales manager: List all locales / supported locales, change default locale / supported locales on the fly, and more.
  • Made with ❤️ & ☕.

Table of contents

  1. Installation and Setup
  2. Configuration
  3. Usage
  4. FAQ

Contribution

Any ideas are welcome. Feel free to submit any issues or pull requests, please check the contribution guidelines.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

localization's People

Contributors

arcanedev-maroc avatar bee-interactive avatar jochensengier avatar ppshobi avatar salkhwlani avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

localization's Issues

Localised Url Parameter Makes view unable to render

When providing an option path parameter in my localized password reset route, it makes the route unable to render.

In my routes.php have:

Route::transGet('routes.reset_password', [
    'as' => 'reset_form',
    'uses' => 'Auth\PasswordController@showResetForm',
]);

In my en/routes.php file i have

return [
    //...

    'reset_password' => 'password/reset/{token?}'

    //...
];

When I go to the url en/password/reset, the expected view renders fine. However when I visit en/password/reset/sometoken the view just doesn't render and instead just seems to dump and array like ['token' => 'sometoken']. It's using the out of the box PasswordController for Laravel 5.2

Translation doesnt persist?

So I have two locales: en and hr.

I have to routes files. One in /app/Http/routes.php

and other one in /vendor/laravel/spark/src/Htpp/routes.php (assigns routes to $router variable)

Now when I got to /dashboard which is defined in original Laravel routes.php like this

Route::localizedGroup(function () {
    /*  Middleware Auth  */
    Route::group(['prefix' => 'dashboard', 'middleware' => ['auth', 'subscribed']], function () {
        Route::get('/', [
            'as' => 'dashboard',
            'uses' => 'DashboardController@index'
        ]);
    });
    // ...

and then it takes me to /en/dashboard or /hr/dasdashboard. That's great. And there I switch to /en/dashboard

Then I go to '/settings' route. No locale prefixed and it always takes me to /hr/settings but I was on /en/dashboard.

Why does it change locale for no reason? That route '/settings' is defined in Spark's routes.php

$router->group([
    'prefix'     => Localization::setLocale(),
    'middleware' => [
        'localization-session-redirect',
        'localization-redirect',
    ],
], function($router) {
    $router->group(['middleware' => 'web'], function ($router) {

    // ...
       // Settings Dashboard...
        $router->get('/settings', 'Settings\DashboardController@show');
    // ...

Also my localization.php

    /* ------------------------------------------------------------------------------------------------
     |  Settings
     | ------------------------------------------------------------------------------------------------
     */
    'supported-locales'      => ['en', 'hr'],

    'accept-language-header' => true,

    'hide-default-in-url'    => false,

    'facade'                 => 'Localization',

    /* -----------------------------------s-------------------------------------------------------------
     |  Route
     | ------------------------------------------------------------------------------------------------
     */
    'route'                  => [
        'middleware' => [
            'localization-session-redirect' => true,
            'localization-cookie-redirect'  => false,
            'localization-redirect'         => true,
            'localized-routes'              => true,
            'translation-redirect'          => true,
        ],
    ],

So why Locale /en doesnt persist and why is it always changed to hr???

Extending a class Locale.php

I need to extend your a class in your entities folder called Locale.php for add parameter config.

How do I go about doing that?

Thanks :)

I would like have

<?php

return [
    // ...

    'locales'   => [
        // A
        //====================================================>
        'aa'         => [
            'name'   => 'Afar',
            'script' => 'Latn',
            'dir'    => 'ltr',
            'native' => 'Qafar',
            'datepicker' => 'af'
        ],

        // ...

        'zu'         => [
            'name'   => 'Zulu',
            'script' => 'Latn',
            'dir'    => 'ltr',
            'native' => 'IsiZulu',
            'datepicker' => 'zu'
        ],
    ],
];

instead of

<?php

return [
    // ...

    'locales'   => [
        // A
        //====================================================>
        'aa'         => [
            'name'   => 'Afar',
            'script' => 'Latn',
            'dir'    => 'ltr',
            'native' => 'Qafar',
        ],

        // ...

        'zu'         => [
            'name'   => 'Zulu',
            'script' => 'Latn',
            'dir'    => 'ltr',
            'native' => 'IsiZulu',
        ],
    ],
];`

Localization v1.0.0

TODO

  • Refactoring/Renaming the contracts (interfaces).
  • Adding more regionals for locales.
  • Complete the documentation.

GOALS

  • 100% Code coverage + Maximum code quality.

Suggestions

  • Adding the attributes translator (Helper / Trait) ??
  • Extending the Locale Entity Class (#49).

NOTE : Feel free to post any suggestion or a feature to improve this package.

Localization disables POST requests

I have a strange problem.
I placed my routes in the localization group but it disabled every POST request. I tried moving them out from the group and they actually work. Since I haven't read this problem so far in the internet, I'm asking here for help.

translated routes after setSupportedLocales

If use setSupportedLocales with new languages that not are in 'supported-locales' config the translated routes not work, all of possible new langs should be in supported-locales

hide-url for all language

I use en and es language
Is it possible to hide both url for both url? I know can hide default language from config file.

Problem routing a form to his respective controller

Hi, im having a problem when I try to route a LaravelCollective form to his respective controller, this is the view which contains the form:

@extends('layouts.admin')
@section('content')
{!!Form::open(['route'=>'investigador.store', 'method'=>'POST'])!!}
<Here goes the form fields>
{!!Form::submit('Registrar',['class'=>'btn btn-primary'])!!}
{!!Form::close()!!} 
@endsection

And here my routes.php

<?php
Route::localizedGroup(function () {
    <Other routes>
    Route::resource('investigador', 'InvestigadorController');
});
Route::resource('login', 'LoginController');

When I route the login to the LoginController I don't have any problem because the login method does not need to be translated but when I try to open the view which contains the form I receive this error messages (server and project are example names):

InvalidArgumentException in UrlGenerator.php line 278:
Route [investigador.store] not defined.
in UrlGenerator.php line 278
at UrlGenerator->route('investigador.store') in FormBuilder.php line 943
at FormBuilder->getRouteAction('investigador.store') in FormBuilder.php line 898
at FormBuilder->getAction(array('route' => 'investigador.store', 'method' => 'POST')) in FormBuilder.php line 108
at FormBuilder->open(array('route' => 'investigador.store', 'method' => 'POST')) in Facade.php line 210
at Facade::__callStatic('open', array(array('route' => 'investigador.store', 'method' => 'POST'))) in 85a6f126a152415156083d060d88cd91 line 4
at FormFacade::open(array('route' => 'investigador.store', 'method' => 'POST')) in 85a6f126a152415156083d060d88cd91 line 4
at include('/server/project/storage/framework/views/85a6f126a152415156083d060d88cd91') in PhpEngine.php line 42
at PhpEngine->evaluatePath('/server/project/storage/framework/views/85a6f126a152415156083d060d88cd91', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in CompilerEngine.php line 58
at CompilerEngine->get('/server/project/resources/views/investigador/create.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in View.php line 138
at View->getContents() in View.php line 107
at View->renderContents() in View.php line 81
at View->render() in Response.php line 51
at Response->setContent(object(View)) in Response.php line 202
at Response->__construct(object(View)) in Router.php line 1225
at Router->prepareResponse(object(Request), object(View)) in ControllerDispatcher.php line 113
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
<etcetera>

and

ErrorException in UrlGenerator.php line 278:
Route [investigador.store] not defined. (View: /server/project/resources/views/investigador/create.blade.php)
in UrlGenerator.php line 278
at CompilerEngine->handleViewException(object(InvalidArgumentException), '1') in PhpEngine.php line 44
at PhpEngine->evaluatePath('/server/project/storage/framework/views/85a6f126a152415156083d060d88cd91', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in CompilerEngine.php line 58
at CompilerEngine->get('/server/project/resources/views/investigador/create.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag))) in View.php line 138
at View->getContents() in View.php line 107
at View->renderContents() in View.php line 81
at View->render() in Response.php line 51
at Response->setContent(object(View)) in Response.php line 202
at Response->__construct(object(View)) in Router.php line 1225
at Router->prepareResponse(object(Request), object(View)) in ControllerDispatcher.php line 113
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
at ControllerDispatcher->callWithinStack(object(InvestigadorController), object(Route), object(Request), 'create') in ControllerDispatcher.php line 69
at ControllerDispatcher->dispatch(object(Route), object(Request), 'Project\Http\Controllers\InvestigadorController', 'create') in Route.php line 201
at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
at Route->run(object(Request)) in Router.php line 704
<etcetera>

The rest of the translated pages without forms work fine in all the languages.
Here you have the result of a php artisan route:list on my project.

+--------+----------+----------------------------------+----------------------+-------------------------------------------------------+----------------------------------------------------------------------+
| Domain | Method   | URI                              | Name                 | Action                                                | Middleware                                                           |
+--------+----------+----------------------------------+----------------------+-------------------------------------------------------+----------------------------------------------------------------------+
|        | GET|HEAD | /                                |                      | Project\Http\Controllers\HomeController@index           | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | admin                            |                      | Project\Http\Controllers\HomeController@admin           | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | auth                             |                      | Project\Http\Controllers\HomeController@auth            | localization-session-redirect,localization-redirect,localized-routes |
|        | POST     | investigador                     | investigador.store   | Project\Http\Controllers\InvestigadorController@store   | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | investigador                     | investigador.index   | Project\Http\Controllers\InvestigadorController@index   | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | investigador/create              | investigador.create  | Project\Http\Controllers\InvestigadorController@create  | localization-session-redirect,localization-redirect,localized-routes |
|        | PUT      | investigador/{investigador}      | investigador.update  | Project\Http\Controllers\InvestigadorController@update  | localization-session-redirect,localization-redirect,localized-routes |
|        | DELETE   | investigador/{investigador}      | investigador.destroy | Project\Http\Controllers\InvestigadorController@destroy | localization-session-redirect,localization-redirect,localized-routes |
|        | PATCH    | investigador/{investigador}      |                      | Project\Http\Controllers\InvestigadorController@update  | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | investigador/{investigador}      | investigador.show    | Project\Http\Controllers\InvestigadorController@show    | localization-session-redirect,localization-redirect,localized-routes |
|        | GET|HEAD | investigador/{investigador}/edit | investigador.edit    | Project\Http\Controllers\InvestigadorController@edit    | localization-session-redirect,localization-redirect,localized-routes |
|        | POST     | login                            | login.store          | Project\Http\Controllers\LoginController@store          |                                                                      |
|        | GET|HEAD | login                            | login.index          | Project\Http\Controllers\LoginController@index          |                                                                      |
|        | GET|HEAD | login/create                     | login.create         | Project\Http\Controllers\LoginController@create         |                                                                      |
|        | PATCH    | login/{login}                    |                      | Project\Http\Controllers\LoginController@update         |                                                                      |
|        | PUT      | login/{login}                    | login.update         | Project\Http\Controllers\LoginController@update         |                                                                      |
|        | GET|HEAD | login/{login}                    | login.show           | Project\Http\Controllers\LoginController@show           |                                                                      |
|        | DELETE   | login/{login}                    | login.destroy        | Project\Http\Controllers\LoginController@destroy        |                                                                      |
|        | GET|HEAD | login/{login}/edit               | login.edit           | Project\Http\Controllers\LoginController@edit           |                                                                      |
+--------+----------+----------------------------------+----------------------+-------------------------------------------------------+----------------------------------------------------------------------+

How can I solve this error message?, with the mcamara LaravelLocalizaton module i had the same error, I´ve cleared the caches and begin into a clean new project but i receive the same error.

Thanks in advance.

App::getLocale() is incorrect as is getCurrentLocale outside of Route::localizedGroup

I found a similar issue here:
#44

Even if I switch to Localization::getCurrentLocale() it always defaults to the default language of the site if the middleware is not used on some routes. This was a problem with the original https://github.com/mcamara/laravel-localization package which is why I tried yours.

To be clear, as long as the routes are setup with localizedGroup they work ok but any outside of this return the default site language. We have a custom language setup that really needs to use App::getLocale(). I'd really appreciate it if you could take a look.

Thanks

Session not persisting on Route::transGet routes.

Hi,

I'm working on a multilingual webshop in Laravel 5.2.

Products are added to the cart with an AJAX POST request.

Localization and translated routes are working fine. Love the package!

However when using Route::transGet my session is not persisting. The session and CSRF token are regenerated on each request and I get TokenMismatchException on the AJAX requests.

When I comment out all Route::transGet and use normal routes the session is working fine but off course I don't have the translated routes anymore.

What could be the reason for the session not persisting on transGet routes?

Thanks!

Ben

My Routes:

Route::group(['middleware' => ['web']], function () {
    Route::localizedGroup(function () {
        Route::get('/',                   'PagesController@getVouchers');
        Route::get('/shop/flying-packs',  'PagesController@getPacks');
        Route::get('/shop/gift-vouchers', 'PagesController@getVouchers');
        Route::get('/shop/bag',           'PagesController@getBag');

        //Route::transGet('routes.shop/gift-vouchers',   'PagesController@getVouchers');
        //Route::transGet('routes.shop/flying-packs',    'PagesController@getPacks');
        //Route::transGet('routes.shop/bag',             'PagesController@getBag');
        //Route::transGet('routes.shop/checkout/mydata', 'PagesController@getMydata');

        Route::post('/shop/checkout/mydata',        'PagesController@postMydata');
        Route::get('/shop/checkout/paymentmethod',  'PagesController@getPaymentmethod');
        Route::post('/shop/checkout/paymentmethod', 'PagesController@postPaymentmethod');
        Route::get('/shop/checkout/overview',       'PagesController@getOverview');
        Route::get('/shop/checkout/thankyou',       'PagesController@getThankYou');
    });

    // Ajax routes
    Route::post('/shop/bag/addtobag',                'BagController@addToBag');
    Route::post('/shop/bag/removefrombag/{id}',      'BagController@removeFromBag');
    Route::post('/shop/bag/updatebag/{id}/{amount}', 'BagController@updateBag');
});

AJAX POST request:

$('.add-to-cart-button').click(function(event) {
    var id = $(this).data('product-id');

    $.ajax({
        url:      '/shop/bag/addtobag',
        type:     'POST',
        data:     {'articlecode': id},
        dataType: 'json',
        success: function(data) {
            console.log(data);
            console.log(data['count']);

            var count = data['count'];
            if (count > 0) {
                $('.c-cart-number').fadeIn("slow").text(count);
            } else {
                $('.c-cart-number').hide().text('');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
});

CSRF token is send as header.

<meta name="csrf-token" content="{{ csrf_token() }}" />

And:

$(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
});

Problem with resource route and group prefix

Hi, I've found an error when I set a prefix to a localized route. It can not find the route. I think this error has to do with this issue #5

This is my routes.php:

Route::localizedGroup(function() {

    // Other routes

    Route::group([
        'prefix' => 'admin',
        'namespace' => 'Admin',
        'middleware' => 'auth'
    ], function() {
        Route::resource('users', 'UserController');
    });

});

and my blade page:

{{ route('admin.users.create') }}

Although the route works and the index page is loaded (http://localhost/en/admin/users), it throws this error:

ErrorException in UrlGenerator.php line 278: Route [admin.users.create] not defined.
(View: E:\www\project\resources\views\admin\user\index.blade.php)

    in UrlGenerator.php line 278
    at CompilerEngine->handleViewException(object(InvalidArgumentException), '1') in PhpEngine.php line 44
    at PhpEngine->evaluatePath('E:\www\project\storage\framework\views/a7435d1634574e25b3ea400c55dd12b4', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'models' => object(Collection))) in CompilerEngine.php line 58
    at CompilerEngine->get('E:\www\project\resources\views/admin/user/index.blade.php', array('__env' => object(Factory), 'app' => object(Application), 'errors' => object(ViewErrorBag), 'models' => object(Collection))) in View.php line 135
    at View->getContents() in View.php line 106
    at View->renderContents() in View.php line 80
    at View->render() in Response.php line 51
    at Response->setContent(object(View)) in Response.php line 202
    at Response->__construct(object(View)) in Router.php line 1225
    at Router->prepareResponse(object(Request), object(View)) in ControllerDispatcher.php line 113
    at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 114
    at ControllerDispatcher->callWithinStack(object(UserController), object(Route), object(Request), 'index') in ControllerDispatcher.php line 69
    at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\Admin\UserController', 'index') in Route.php line 201
    at Route->runWithCustomDispatcher(object(Request)) in Route.php line 134
    at Route->run(object(Request)) in Router.php line 704
    at Router->Illuminate\Routing\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Authenticate.php line 44
    at Authenticate->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in LocalizationRoutes.php line 31
    at LocalizationRoutes->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(LocalizationRoutes), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in LocalizationRedirect.php line 42
    at LocalizationRedirect->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(LocalizationRedirect), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in Router.php line 706
    at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 671
    at Router->dispatchToRoute(object(Request)) in Router.php line 631
    at Router->dispatch(object(Request)) in Kernel.php line 236
    at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
    at VerifyCsrfToken->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
    at ShareErrorsFromSession->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
    at StartSession->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
    at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
    at EncryptCookies->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
    at CheckForMaintenanceMode->handle(object(Request), object(Closure))
    at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
    at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
    at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
    at Pipeline->then(object(Closure)) in Kernel.php line 122
    at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
    at Kernel->handle(object(Request)) in index.php line 54

My route list is:

+--------+----------+----------------------------------+-------------------------+-----------------------------------------------------------------+----------------------------------------------+
| Domain | Method   | URI                              | Name                    | Action                                                          | Middleware                                   |
+--------+----------+----------------------------------+-------------------------+-----------------------------------------------------------------+----------------------------------------------+
|        | GET|HEAD | /                                | home                    | App\Http\Controllers\PagesController@home                       | localization-redirect,localized-routes       |
|        | POST     | admin/users                      | admin.users.store       | App\Http\Controllers\Admin\UserController@store                 | localization-redirect,localized-routes,auth  |
|        | GET|HEAD | admin/users                      | admin.users.index       | App\Http\Controllers\Admin\UserController@index                 | localization-redirect,localized-routes,auth  |
|        | GET|HEAD | admin/users/create               | admin.users.create      | App\Http\Controllers\Admin\UserController@create                | localization-redirect,localized-routes,auth  |
|        | PATCH    | admin/users/{users}              |                         | App\Http\Controllers\Admin\UserController@update                | localization-redirect,localized-routes,auth  |
|        | DELETE   | admin/users/{users}              | admin.users.destroy     | App\Http\Controllers\Admin\UserController@destroy               | localization-redirect,localized-routes,auth  |
|        | GET|HEAD | admin/users/{users}              | admin.users.show        | App\Http\Controllers\Admin\UserController@show                  | localization-redirect,localized-routes,auth  |
|        | PUT      | admin/users/{users}              | admin.users.update      | App\Http\Controllers\Admin\UserController@update                | localization-redirect,localized-routes,auth  |
|        | GET|HEAD | admin/users/{users}/edit         | admin.users.edit        | App\Http\Controllers\Admin\UserController@edit                  | localization-redirect,localized-routes,auth  |
+--------+----------+----------------------------------+-------------------------+-----------------------------------------------------------------+----------------------------------------------+

Thanks in advance!

support relative URLs in getLocalizedURL()

Function works properly only with absolute URLs. 'laravel-localization' package's getLocalizedURL() managed to work with relative URLs too.

mcamara/laravel-localization#47 (comment)

This is my dirty fix.

$url = Url::unparse($parsedUrl);

if ($url) {
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        return $url;
    }
} else {
    return "/" . ltrim($parsedUrl['path'], '/');
}

return $this->createUrlFromUri($url);

Auth Login POST (with wrong credentials) redirects to home?

I localized all Auth routes.

When I go to Login and enter wrong credentials and submit it, I get redirected to home route? Any ideas or suggestion to why this might be happening?

$router->group([
    'prefix'     => Localization::setLocale(),
    'middleware' => [
        'web',
        'localization-session-redirect',
        'localization-redirect',
    ],
], function($router) {
    $router->group([
            'as'        => 'auth::',
            'namespace' => 'Auth',
        ], 
        function ($router) {
            // Authentication Routes...
            $router->group(['prefix' => 'login', 'as' => 'login.'], function ($router) {
                // auth::login.get
                $router->get('/',  ['as' => 'get',  'uses' => 'LoginController@showLoginForm']);
                // auth::login.post
                $router->post('/', ['as' => 'post', 'uses' => 'LoginController@login']);
            });

            // auth::logout
            $router->get('logout', ['as' => 'logout', 'uses' => 'LoginController@logout']);

            // Registration Routes...
            $router->group(['prefix' => 'register', 'as' => 'register.'], function ($router) {
                // auth::register.get
                $router->get('/',  ['as' => 'get',  'uses' => 'RegisterController@showRegistrationForm']);
                // auth::register.post
                $router->post('/', ['as' => 'post', 'uses' => 'RegisterController@register']);
            });
        }
    );
});

Route::auth() validation issue!!!

Validation not work in localizedGroup:

Route::localizedGroup(function () {
    // ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP

    Route::auth();
});

Please help to fix this issue!
Laravel Framework version 5.2.30
php artisan make:auth
Thank you

localization not saved between pages.

Hi,

I am using your package for my Laravel application localization,
i follow each step in the docs, everything looks great except one issue :
when i redirect to my site like this :

www.mysite.com/fr

Im getting my site in FR like i expected. but when i click on some link inside the page, im getting back the the fallback lang, "en".
its not keeping the selected local between redirect of pages.

  • my Laravel session cookie driver is : SESSION_DRIVER=file
  • the session directory has permissions to writ the sessions file, they are created for each visit & login.
  • i cleared the app cache and config files,

*the localization config is :

<?php

    'route' => [
        'middleware' => [
            'localization-session-redirect' => true,
            'localization-cookie-redirect'  => false,
            'localization-redirect'         => true,
            'localized-routes'              => true,
            'translation-redirect'          => true, 
        ],
    ], 
  • my routs definition is like this :
<?php
Route::group([
    'prefix'     => Localization::setLocale(),
    'middleware' => [
        'localization-session-redirect',
        'localization-redirect',
        'web'
    ],
], function () {
     //all my Routes that used the translation are in here....
});

how can i fix this?
thanks!

Extending a class

I need to extend your a class in your entities folder called Locale.php.

How do I go about doing that?

[Question] - Locales config variables

Hi Arcanedev,

Is it possible to forgo locales variables ('script' & 'dir') located in config/localization.php?

The reason i'm asking this is because my website uses Country-based routes instead of Language-based routes like /us instead of /en.

Persistent Locale

Hi, i just install this package. But I'm a little confused.

I have config/app.php with:

'locale' => 'es',

And config/localization.phpas:

'supported-locales'      => ['en', 'es'],

    'accept-language-header' => true,

    'hide-default-in-url'    => false,

    'facade'                 => 'Localization',

    /* ------------------------------------------------------------------------------------------------
     |  Route
     | ------------------------------------------------------------------------------------------------
     */
    'route'                  => [
        'middleware' => [
            'localization-session-redirect' => true,
            'localization-cookie-redirect'  => false,
            'localization-redirect'         => true,
            'localized-routes'              => true,
            'translation-redirect'          => true,
        ],
    ],

I have and admin panel without routes translates. And In my views if I call dump(\App::getLocale()), allways get en neveres. But es is the default language. If I call dump(\App::getLocale()) in routes.php file shows es.

But If I call Localization::getCurrentLocale()shows correctly es.

My route is for example: blog/new. And Route is not in localization middleware:

Route::group(['prefix' => 'admin', 'middleware' => 'role:admin'], function() 
{
    Route::get('/blog/new', '\App\Blog\Controllers\PostController@create');
});

Why locale is set to en? How can I do it?

Thanks!

Navbar issue with the route bindings

I could try out your package as I said.

I like some stuff that you cleaned a bit up from mcamara/laravel-localization like the transGet, transPost and also the localizedGroup.

But my main Problem still exists.. but a bit different. If I use model binding with named parameter, the localsNavbar returns the Hole Model Object Data in the URL:

<ul class="navbar-locales">
    <li class="active">
        <a href="http://torebuild1.local/de/firma/abdeckung/{"id":2,"name":"<j\u00f6","strasse":"575 Wiegand View Suite 800","plz":"999.99","ort":"Howeville","telefon":"053.534.4705x49474","email":"cSchamberger@Nitzsche.com","created_at":"2015-12-05 14:24:19","updated_at":"2015-12-10 12:58:49","bereiche":[{"id":1,"name":"umzug","aktiv":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","pivot":{"firma_id":2,"bereich_id":1,"created_at":"2015-12-08 10:22:17","updated_at":"2015-12-08 10:22:17"}}]}" rel="alternate" hreflang="de"> 
            Deutsch 
        </a>
    </li> 
    <li class="">
        <a href="http://torebuild1.local/en/company/coverageEN/{"id":2,"name":"<j\u00f6","strasse":"575 Wiegand View Suite 800","plz":"999.99","ort":"Howeville","telefon":"053.534.4705x49474","email":"cSchamberger@Nitzsche.com","created_at":"2015-12-05 14:24:19","updated_at":"2015-12-10 12:58:49","bereiche":[{"id":1,"name":"umzug","aktiv":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","pivot":{"firma_id":2,"bereich_id":1,"created_at":"2015-12-08 10:22:17","updated_at":"2015-12-08 10:22:17"}}]}" rel="alternate" hreflang="en"> 
            English 
        </a> 
    </li> 
    <li class="">
        <a href="http://torebuild1.local/fr/entreprise/abdeckungFR/{"id":2,"name":"<j\u00f6","strasse":"575 Wiegand View Suite 800","plz":"999.99","ort":"Howeville","telefon":"053.534.4705x49474","email":"cSchamberger@Nitzsche.com","created_at":"2015-12-05 14:24:19","updated_at":"2015-12-10 12:58:49","bereiche":[{"id":1,"name":"umzug","aktiv":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00","pivot":{"firma_id":2,"bereich_id":1,"created_at":"2015-12-08 10:22:17","updated_at":"2015-12-08 10:22:17"}}]}" rel="alternate" hreflang="fr"> 
            Français 
        </a> 
    </li> 
</ul> 

EDIT :
But the translation of the Route is right!!
So if you can fix that, I will never go back to the other package ;-)

Access level to Arcanedev\Localization\LocalizationServiceProvider::publishConfig() must be protected

Hi,

When i "composer update" :
[...]

  • Removing arcanedev/support (3.7.5)
  • Installing arcanedev/support (3.8.0)
    [...]

I have this error :
[...]
PHP Fatal error: Access level to Arcanedev\Localization\LocalizationServiceProvider::publishConfig() must be protected (as in class Arcanedev\Support\PackageServiceProvider) or weaker in /Users/vince/Sites/projects/dujour/menu/vendor/arcanedev/localization/src/LocalizationServiceProvider.php on line 11

Thanks

Translated routes redirect

I'm in a weird situation. I hope someone can help me.

Only the translated routes in es/routes.php gets redirected.

//// productos means products in spanish

Behaviour:
// with locale == es
project.dev/productos -> project.dev/es/productos
project.dev/products -> 404

// with locale == en
project.dev/productos -> project.dev/en/products
project.dev/products -> 404

es/routes.php
return [ 'products' => 'productos' ];

en/routes.php
return [ 'products' => 'products' ];

routes file
Route::transGet('routes.products', 'PublicPagesController@showProducts');

with middlewares

'localization-session-redirect', 'localization-redirect'

Laravel 5.3 Validation localized Massages - Shows Only default (en)

Hi.
i have Laravel 5.3 application with ARCANEDEV/Localization pack, work greate so far! :)
i have right now an issue with the validation massages.

this is my Routes:

Route::group(['middleware' => ['web']], function () {
    Auth::routes();
    Route::group([
        'prefix'     => Localization::setLocale(),
        'middleware' => [
            'localization-session-redirect',
            'localization-redirect',
            'localized-routes'
        ],
    ], function() {

    // All Routes in here! 
    // Including some of the Auth GET methods (register & login page & reset password),
    // not the post routes.
    });
});

in the lang file i have this (/resources/lang/en/validation.php):

'custom' => [
    'g-recaptcha-response' => [
        'captcha' => 'Are you a Robot?',
    ],
],

in the blade template i have this :

<label class="input">
    {!! app('captcha')->display($attributes = [], $lang = Localization::getCurrentLocale()); !!}
    @if ($errors->has('g-recaptcha-response'))
	<span class="help-block">
	<strong>{{ $errors->first('g-recaptcha-response') }}</strong>
	</span>
    @endif
</label>
  • the problem is that i have the translation for this captcha attribute, in more 2 languages.
    no metter which language i am, im getting the "en" text not the actual local of the current user.
    all the other translation in the php code & the blade template are working fine, this issue is only regarding the validation errors.

what could be the problem?

transPost Bug

Hi

It looks like there is a bug in transPost:

I have a form:

<form method="POST" action="/firma/profile/{{ $firma->id }}">

resources/lang/de/routes.php:

'firma-profile-id' => 'firma/profile/{id}',

And in my /http/routes.php:

Route::transGet('routes.firma-profile-id',  'FirmaController@profile');
Route::transPost('routes.firma-profile-id', 'FirmaController@update');

What happens:

  • it does not call the FirmaController@update method ->but it should
  • it does call the FirmaController@profile method ->but it shouldn't

EDIT :
The FirmaController@profile is called from the transPost and not from the transGet. If I take out the transPost Line, the transGet rightly does not get called..

User selected language

I'd like to display a choice of languages when a user first visits my site and then redirect the user to their chosen language and store the choice in a cookie so that they don't get asked again on subsequent visits. However I can't work out how to do this, any help would be much appreciated.

Laravel 5.2 support

I've tested if the package already works with Laravel 5.2, unfortunatelly it's not. I get the exception:

ErrorException in RouteTranslator.php line 165: Object of class Illuminate\Routing\UrlGenerator could not be converted to string

composer update error

I'm using App::setlocale at provider, but then with composer update, crash:

Arcanedev\Localization\Exceptions\UnsupportedLocaleException]
Laravel default locale [] is not in the supported-locales array.

I need quit App:setLocale to use composer, but I need do it for my use of the app.

Set locale based on country?

I use cloudflare. They provide visitor's country code.

What would be the best way to make sure that the visitor is set to locale that matches his country?

Performance

Currently I have about 25 translated routes in my routes file. Since that, the performance got very worse. If I use route:cache the performance would be good, but then the translated routes would not work.

Perhaps it's something different, or does anybody of you guys have the same issue?

Getting localized urls for nested route groups not working beyond first level of depth

I have an issue where I cannot get nested route groups translated beyond the first level of depth when using the language switcher:

Route::localizedGroup(function () {
    Route::transGet('routes.webhosting.colocation', ['as' => 'webhosting.colocation', 'uses' => 'WebhostIngcontroller@colocatie']);

    Route::group(['prefix' => trans('routes.webhosting')], function () {

    Route::transGet('routes.webhosting.colocation', ['as' => 'webhosting.colocation', 'uses' => 'WebhostIngcontroller@colocatie']);
    });
}); 

The first route within the localizedGroup does the job, but the one in the group doest first not translate the group prefix and second does not translate the route name when I want to switch the language.

The languages/[lang]/routes.php files looks like this:

languages/en/routes.php
    'webhosting'                        => 'hosting',
    'webhosting.colocation'       => 'colocation',

languages/nl/routes.php --> dutch
    'webhosting'                        => 'webhosting',
    'webhosting.colocation'       => 'colocatie',

I would assume the following routes when I change from one to the other language in the language switcher:

nl --> domain.app/nl/webhosting/colocatie
en --> domain.app/en/hosting/colocation

But I get the following switching from NL to EN

nl --> domain.app/nl/webhosting/colocatie
en --> domain.app/en/webhosting/colocatie

I can work a round with attaching the prefix to the translation but that does not feels nice.

Undefined variable: supportedLocales

followed your configuration and used following code for menu

@foreach($supportedLocales as $key => $locale)
    <li class="{{ localization()->getCurrentLocale() == $key ? 'active' : '' }}">
        <a href="{{ localization()->getLocalizedURL($key) }}" rel="alternate" hreflang="{{ $key  }}">
            {{ $locale->native() }}
        </a>
    </li>
@endforeach

I am getting following error. anyone can help me to fix this? I want to display language switcher

Undefined variable: supportedLocales

Method localizedGroup does not exist.

Hello,

I'm trying this package from mcamara/laravel-localization, but I get the error in the subject of this issue.

I registered the provider and the kernel trait, what I'm wrong?

Problem calling translation form other source different to resources/lang (Modular app)

Hi!,

I'm developing a modular Laravel app, in each module I have controllers, views, translations and routes. Your package works perfect in each isolated routes.php file. The problem is when I try to translate a route, for example:

<?php

// app/Modules/Module1/routes.php

Route::group(['module' => 'Module1', 'namespace' => 'App\Modules\Module1\Controllers'], function() {
    Route::localizedGroup(function () {
        Route::transGet('Module1::routes.destinations, 'Module1Controller@index');
    });
});

At this point seems to be the 'transGet' function can't localize the translation.

In my views I implement the 'trans' helper this way, without any problem...

{{ trans('Module1::home.title') }}

Here I can see how your package implements the 'trans' method:

https://github.com/ARCANEDEV/Localization/blob/master/src/Utilities/RouteTranslator.php#L246

Can you help me with some clues?

This is my service provider:

// app/Providers/ModuleServiceProvider.php

class ModuleServiceProvider extends ServiceProvider {

    protected $files;

    public function boot() {

        if(is_dir(app_path().'/Modules/')) {
            $modules = config("modules.enable") ?: array_map('class_basename', $this->files->directories(app_path().'/Modules/'));
            foreach($modules as $module)  {
                // Allow routes to be cached
                if (!$this->app->routesAreCached()) {
                    $routes = app_path() . '/Modules/' . $module . '/routes.php';
                    if($this->files->exists($routes)) include $routes;
                }
                $views  = app_path().'/Modules/'.$module.'/Views';
                $trans  = app_path().'/Modules/'.$module.'/Translations';

                if($this->files->isDirectory($views)) $this->loadViewsFrom($views, $module);
                if($this->files->isDirectory($trans)) $this->loadTranslationsFrom($trans, $module);
            }
        }
    }

    public function register() {
        $this->files = new Filesystem;
    }
}

This is my folder structure:

app
...
|-- Modules
|   |-- Module1
|   |   |-- Controllers
|   |   |   `-- Module1Controller.php
|   |   |-- Translations
|   |   |   |-- en
|   |   |   |   `-- routes.php
|   |   |   `-- es
|   |   |       `-- routes.php
|   |   |-- Views
|   |   |   |-- index.blade.php
|   |   `-- routes.php
|   `-- Module2
|       |-- Controllers
|       |   `-- Module2Controller.php
|       |-- Translations
|       |   |-- en
|       |   |   `-- routes.php
|       |   `-- es
|       |       `-- routes.php
|       |-- Views
|       |   |-- index.blade.php
|       `-- routes.php
...

Thanks in advance.

PHP version

Hi,

Since your package is supporting from Laravel 5.0.x, could you consider to reduce the php version to >=5.4 in the composer.json requirements?

Thanks.

Problem with getLocales()

I'm doing this in my locales middleware:
Localization::setSupportedLocales(['en', 'fr']);
but when I'm doing this in my controller:

$languages = MYMODEL::getLocales();
dd($languages);

I'm getting this: en,fr,es

My model extends Model and use \Dimsav\Translatable\Translatable

Any idea why
Localization::getSupportedLocales();
is correct but
MYMODEL::getLocales()
is NOT correct?

Localization facade not found

It hasn't done automatically. I need to register it in config/app.php and it works fine.
P/S: I am using Laravel 5.2

getLocalizedUrl returns only default lang url when artisan route:cache run

E.g. \Localization::getLocalizedUrl('de', route('about')) will produce an English (my app's default language) url instead of the proper transRoute url due to Laravel 5's route caching. If I artisan route:clear everything works as normal. A major dilemma is without route caching my app will run too slow for production, on the other hand with cache my app will run faster but the urls will be wrong. Is there any way to fix this?

Issue with middlewares under Laravel 5.2

The provided Router class does not preserve middleware groups as defined in Kernel.php.
For instance, following middleware group definitions are simply ignored:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

resulting in web or api class not found error while processing routes that include such middleware groups.

It seems that the approach to extend default Router needs to be reviewed in Laravel 5.2 (http://blog.lanin.me/extending-default-laravel-router/).

Please, make sure to update default Router extension according to Laravel 5.2 design.
Thank you.

help pls

hello, i dont understand this can anyone help me

this is my routes file

<?php

Route::localizedGroup(function () {

    Route::group(['middleware' => 'web'], function () {

        Route::get('/', 'Frontend\HomeController@home')->name('frontend.index');

        Route::get('login', 'Auth\AuthController@getLogin');

    });

});

so when i change my language to NL or TR it works fine in homepage, but when i click to /login it redirects me to the default locale /en/login
so how do i make sure it stays to the selected language ?

Route::resource not translate url

I need to translate my entirely url and try with Route::resource('routes.users', 'UsersController'); but return 404 page :(

My routes.php file:

Route::localizedGroup(function () {
    Route::transGet('routes.welcome', function () { return view('welcome'); });
    Route::resource('routes.users', 'UsersController');
});

Results:
en/welcome work
es/bienvenido work
en/users fail
es/usuarios fail

Try change line Route::resource('routes.users', 'UsersController'); to Route::resource('users', 'UsersController');
en/users work
es/usuarios fail

Question against mcamara package

Hey there !
I found your package from a macmara Github issue, so i would like to ask you few things to know if your package encounter the same problem that i have with Macmara's one (wich is still really great).

  • I got the same problem as here, idk if it's due to model binding, but some URL works (language switcher correctly change the translated word in URL + code), some URL dont (language switcher just change the code in url, not translated word) all using getLocalizedURL()

View are translated on the second load

Hello,

I (supposely) setup Localization as it should be, but I can't figure out why my view refuses to be translated on the first load.
When I click on the (out-of-the-box) navbar, my url change, my debug output in my welcome.blade.php

{{ config('app.locale') }}
{{ \App::getLocale() }}

shows the correct language code, but my view does not change. I have to reload the page one in order to have the correctly translated page.

I can't understand what is my mistake ?
Do you have any clue ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.