Create API that supports localization.

Submitted by Mahmoud_Zalt - 7 years ago

Support multi languages JSON response

//>> 1) create a middleware

use Closure;
use Illuminate\Foundation\Application;

/**
 * Class Localization
 *
 * @author  Mahmoud Zalt  <mahmoud@zalt.me>
 */
class Localization
{

    /**
     * Localization constructor.
     *
     * @param \Illuminate\Foundation\Application $app
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // read the language from the request header
        $locale = $request->header('Content-Language');

        // if the header is missed
        if(!$locale){
            // take the default local language
            $locale = $this->app->config->get('app.locale');
        }

        // check the languages defined is supported
        if (!array_key_exists($locale, $this->app->config->get('app.supported_languages'))) {
            // respond with error
            return abort(403, 'Language not supported.');
        }

        // set the local language
        $this->app->setLocale($locale);

        // get the response after the request is done
        $response = $next($request);

        // set Content Languages header in the response
        $response->headers->set('Content-Language', $locale);

        // return the response
        return $response;
    }
}




//>> 2) Register the middleware in the Middlewares


//>> 3) add this to the app.php config file

'supported_languages' => ['en' => 'English', 'ru' => 'Russian'],


//>> 4) create language folder in the lang folder "resources/lang" for your language  (in this case it is [ru] next to [en]) and of course set your files there.


//>> 5) create sample route to test this: {you need to use the `trans` function}

Route::get('welcome', function () {

    echo trans('messages.welcome');

});


//>> 6) call the endpoint “http://api.xxxxx.dev/welcome/“ and set the header "Content-Language" in your request to ([en] or [ru]).