404使用区域设置时未找到

时间:2018-05-21 11:14:56

标签: php laravel laravel-5 laravel-5.2 laravel-5.1

我正在使用middlleware在英语和阿拉伯语之间切换

<?php

namespace App\Http\Middleware;

use Closure;

class ApplyLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $segments = collect($request->segments());

        $locale = $segments->first();

        if (! in_array($locale, config('app.locales'))) {
            $locale = 'ar';
            app()->setLocale($locale);
            $segments->prepend($locale);

            return redirect($segments->implode('/'));
        }

        app()->setLocale($locale);

        return $next($request);
    }
}

并在helper.php中我用它来切换

/**
 * @return string
 */
function switchLocaleUrl()
{
    $locale = config('app.locale');

    if ($locale === 'ar') {
        return '/en/' . collect(Request::segments())->splice(1)->implode('/');
    }
    return '/ar/' . collect(Request::segments())->splice(1)->implode('/');
}

并且在视图中我使用:

  <li><a href="{{ switchLocaleUrl() }}"><i class="hvr-float-shadow"></i> {{ config('app.locale') === 'en' ? 'عربي' : 'ENGLISH' }}</a></li> 

但是当我去url localhost / myproject / ar时 错误404 NOT FOUND发生了

2 个答案:

答案 0 :(得分:0)

中间件处理程序中存在拼写错误

使用config('app.locale')代替config('app.locales')

答案 1 :(得分:0)

  1. config / app.php

    中添加包含可用语言的数组

    'languages'=&gt;数组('en','fr','de','es')

  2. 将此代码添加到 filters.php

  3. 应用::之前(函数($请求)     {

     if ( in_array(Request::segment(1), Config::get('app.languages')) ) {
    
        Session::put('locale', Request::segment(1));
        return Redirect::to(substr(Request::path(), 3));
    
     }
      if ( Session::has('locale') ) {
    
        App::setLocale(Session::get('locale'));
    
      }
    
    });