mercredi 29 août 2018

How to 'use' packages in my own Laravel middleware?

I wrote a localization middleware in Laravel using the LaravelGettext package which looks like this:

<?php

namespace App\Http\Middleware;

use Closure;

class Locale {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        if ($request->method() === 'GET') {
            $segment = $request->segment(1);

            if (!in_array($segment, config('laravel-gettext.supported-locales'))) {
                $segments = $request->segments();
                $fallback = session('locale') ?: config('laravel-gettext.fallback-locale');
                $segments = array_prepend($segments, $fallback);

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

            session(['locale' => $segment]);
            LaravelGettext::setLocale($segment);
        }
        return $next($request);
    }

}

I am routing into the middleware via:

Route::prefix('{lang?}')->middleware('locale')->group(function () {
    ...
}

Running through the middleware gives me this error though:

"Class 'App\Http\Middleware\LaravelGettext' not found"

So I figured I might have to import the LaravelGettext package manually by adding:

use Xinax\LaravelGettext\LaravelGettext;

Which now gives me this Exception:

"Non-static method Xinax\LaravelGettext\LaravelGettext::setLocale() should not be called statically"

Which makes me wonder: Is there even a valid option to access the package inside a middleware? Or did I drive into a design flaw here?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2wqLura
via IFTTT

Aucun commentaire:

Enregistrer un commentaire