In today’s globalized world, having a blog that supports multiple languages can be highly beneficial for reaching a wider audience.
The combination of Laravel, a powerful PHP framework, and Vue.js, a popular JavaScript framework, can help you achieve this goal efficiently.
In this blog, we’ll walk you through the process of creating a multi-language blog using Laravel and Vue.js.
We will cover the following topics in this blog:
- Setting up Laravel and Vue.js
- Creating the blog models and migrations
- Implementing localization in Laravel
- Building a Vue.js front-end
- Integrating Laravel and Vue.js for multi-language support
- Testing
- Conclusion
Setting up Laravel and Vue.js
Before diving into the code, ensure that you have the following tools installed on your system:
- Composer
- Node.js and npm
- Laravel Installer
First, create a new Laravel project using the following command:
Using Laravel installer:
laravel new multi-language-blog
Using Composer:
composer create-project --prefer-dist laravel/laravel multi-language-blog
After the installation is complete, navigate to the project directory:
cd multi-language-blog
Next, we will install the Laravel frontend scaffolding. This provides a starting point for integrating Vue.js into our application. To install it, run:
composer require laravel/ui
Now, generate the basic scaffolding for Vue.js:
php artisan ui vue
Finally, install the necessary npm dependencies:
npm install
Creating the blog models and migrations
For our multi-language blog, we’ll need the following models:
- Post
- Language
- PostTranslation
First, create the models and migrations with the following commands:
php artisan make:model Post -m
php artisan make:model Language -m
php artisan make:model PostTranslation -m
Now, let’s define the relationships between these models. Update the Post
, Language
, and PostTranslation
models as follows:
// app/Models/Post.php
class Post extends Model
{
protected $fillable = ['user_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function translations()
{
return $this->hasMany(PostTranslation::class);
}
}
// app/Models/Language.php
class Language extends Model
{
protected $fillable = ['code', 'name'];
public function translations()
{
return $this->hasMany(PostTranslation::class);
}
}
// app/Models/PostTranslation.php
class PostTranslation extends Model
{
protected $fillable = ['post_id', 'language_id', 'title', 'content'];
public function post()
{
return $this->belongsTo(Post::class);
}
public function language()
{
return $this->belongsTo(Language::class);
}
}
Now, let’s update the migrations for each model.
// database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
// database/migrations/xxxx_xx_xx_xxxxxx_create_languages_table.php
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('code', 5)->unique();
$table->string('name')->unique();
$table->timestamps();
});
// database/migrations/xxxx_xx_xx_xxxxxx_create_post_translations_table.php
Schema::create('post_translations', function (Blueprint $table) {
$table->id();
$table->foreignId('post_id')->constrained()->onDelete('cascade');
$table->foreignId('language_id')->constrained()->onDelete('cascade');
$table->string('title');
$table->text('content');
$table->timestamps();
});
After updating the migrations, run the following command to create the database tables:
php artisan migrate
Implementing localization in Laravel
To support multiple languages in Laravel, we need to create translation files for each language. In this example, we’ll support English (en) and Spanish (es). First, create the necessary folders and files:
resources/lang/en/messages.php
resources/lang/es/messages.php
Now, add some translations to the files:
// resources/lang/en/messages.php
<?php
return [
'welcome' => 'Welcome to our multi-language LaravelTuts blog!'
];
// resources/lang/es/messages.php
<?php
return [
'welcome' => '¡Bienvenido a nuestro LaravelTuts blog multilingüe!'
];
In your config/app.php
file, set the locale
and fallback_locale
:
'locale' => 'en',
'fallback_locale' => 'en',
To change the application’s locale, use the following method:
app()->setLocale($locale);
Building a Vue.js front-end
First, create a new Vue component for the blog:
resources/js/components/Blog.vue
In the Blog.vue
file, add the following template and script:
<template>
<div>
<h1>{{ message }}</h1>
<!-- Rest of the blog content -->
</div>
</template>
<script>
export default {
data() {
return {
message: '',
};
},
created() {
axios.get('/api/welcome-message').then((response) => {
this.message = response.data.message;
});
},
};
</script>
Integrating Laravel and Vue.js for multi-language support
Create a new API route in routes/api.php
:
Route::get('/welcome-message', function () {
return response()->json(['message' => trans('messages.welcome')]);
});
In your resources/views/welcome.blade.php
file, replace the existing content with the following:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multi-Language Blog - LaravelTuts</title>
@vite(['resources/js/app.js'])
</head>
<body>
<div id="app">
<blog></blog>
</div>
</body>
</html>
Lastly, register the Blog
component in resources/js/app.js
:
Vue Older:
import Blog from './components/Blog.vue';
const app = new Vue({
el: '#app',
components: { Blog },
});
Vue New:
import Blog from './components/Blog.vue';
app.component('blog', Blog);
Testing
Run the Laravel development server:
Open your terminal and navigate to the project directory, then run the following command:
php artisan serve
This command starts the Laravel development server at http://127.0.0.1:8000 by default. You should see the following message in your terminal:
Starting Laravel development server: http://127.0.0.1:8000
Access the blog in your web browser:
Open your preferred web browser and visit http://127.0.0.1:8000. You should see the multi-language blog with the welcome message displayed in English.
Test the multi-language functionality:
To test the multi-language functionality, you need to implement a language switcher in your Vue.js component. Add the following code to your Blog.vue
file:
<template> <div> <button @click="changeLanguage('en')">English</button> <button @click="changeLanguage('es')">Español</button> <h1>{{ message }}</h1> <!-- Rest of the blog content --> </div> </template>
Add the changeLanguage
method to the methods
object in the script
section of Blog.vue
:
methods: { changeLanguage(lang) { axios.get(`/api/welcome-message?lang=${lang}`).then((response) => { this.message = response.data.message; }); }, },
Update your API route in routes/api.php
to accept the lang
query parameter:
Route::get('/welcome-message', function (Request $request) { $lang = $request->query('lang', 'en'); app()->setLocale($lang); return response()->json(['message' => trans('messages.welcome')]); });
Now, navigate to your multi-language blog at http://127.0.0.1:8000, and test the language switcher by clicking the “English” and “Español” buttons. The welcome message should change according to the selected language.
Conclusion
In this blog, we have walked you through the process of creating a multi-language blog using Laravel and Vue.js. By following these steps, you can create a blog that supports multiple languages and dynamically displays translated content to users based on their language preferences.
While this example focuses on a simple blog, the concepts of using Laravel and Vue.js for multi-language support can be applied to any web application. By leveraging the power of these two frameworks, you can create web applications that cater to a diverse, global audience.