Multilingual E-commerce API using Laravel 8.0 – Passing Information into the headers

Now that we have done the initial setup and add some data into the database using the seeders and factories, let’s see how we can pass some data using headers into our controller.

Since this is a multilingual API, we need to pass the language code with each API request. We are going to use http headers to pass this information.

Please note that at this point you will need the PostmanAPI client installed in your browser using an extension or as a desktop app.

php artisan make:middleware CheckLocale

The above command should create a new middleware file in the app/Http/Middleware folder.

We will add the code to check the header information in the handle() methond. By default the language will be en-gb if the language code is not passed in the header.

In this case we are using X-localisation as the header variable but this can be anything of your choice.

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $local = ($request->hasHeader('X-localization')) ? $request->header('X-localization') : 'en-gb';
     
        app()->setLocale($local);
        return $next($request);
    }

Once we get the language code we use the setLocale() method of Laravel to set the language code.

Series Navigation<< Multilingual E-commerce API using Laravel 8.0 – Part 3 Product Resource and Product Resource CollectionMultilingual E-commerce API using Laravel 8.0 – Part 8 Product Request Object >>