Middleware to Verify the es/en language prefix

The next development that we are going to carry out is to use a middleware to detect the language configured by the user and establish it using the translation text strings that we defined before, in addition, we also define the acronym or language label in the URL to return the translation accordingly. ; for it:

$ php artisan make:middleware LanguagePrefixMiddleware

Which will have the following content:

app\Http\Middleware\LanguagePrefixMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class LanguagePrefixMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {

        $language = $request->segment(1);
        
        if(!in_array($language,['es','en'])){
            return redirect('/es/blog');
        }

        app()->setLocale($language);

        return $next($request);
    }
}

With the above code, it is only redirected when language tags are not available in the URL, then the corresponding language is set.

And we use the middleware in the routes:

Route::get('/{lang}/mi-ruta', 'MiControlador@miMetodo');

For example, in our application:

function routeBlog() {
    Route::get('', [BlogController::class, 'index'])->name('blog.index');
    Route::get('detail/{id}', [BlogController::class, 'show'])->name('blog.show');
}

Route::group(['prefix' => '{locale}/blog','middleware' => LanguagePrefixMiddleware::class], function () {
    routeBlog();
});

Route::group(['prefix' => 'blog','middleware' => LanguagePrefixMiddleware::class], function () {
function () {
    routeBlog();
});

As you can see, we created a routeBlog() function to group the routes to which we want to verify the use of the language, in this example, those of the blog, so that it can be consumed through locale:

es/blog/*

en/blog/*

And without the locale, and in this case, it is redirected to the Spanish language according to the redirection defined in the middleware:

blog/*

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.