In this blog we will focus on how to implement multilingual in API response messages in laravel/lumen.
When providing API Service, sometimes we need to set multiple language for handling response. For example, for servicing mobile apps that has multi language support, user needs to get proper active language message in their app. We do not want user who already set Indonesian as current app language but get an English language in response message.
How to Accomplish Dynamic Language?
Laravel provides multi language support. Simplest thing is define language using request header.
we can use X-localization header key to determine what language is used. Or in other approach we use X-localization attribute as URL query string. But in this case, I’ll recommend to use it as header request.
Language Setup
Lets take a look in lang folder under resources directory then create folder for our language and create file messages.php to assigned our messages. We may may create many language file depends on our available contexts
In messages.php file, we simply returned array that contains our messages.
Under lang/en/messages.php
<?php
return [
‘greeting’ => ‘Hello world. This is using english.’
];
Under lang/id/messages.php
<?php
return [
‘greeting’ => ‘Hello world. Ini menggunakan Bahasa Indonesia.’
];
We’re done to setup our language here, so next we will create our middleware.
In this middleware, we are checking incoming request header and set app locale. We set default localizaton if incoming request has no header for localization, then we continue incoming request.
Created middleware must be registered to app/Http/Kernel.php inside variable routeMiddleware.
We have registered localization middleware, then we should be able to call it in our route. Let’s create a simple controller to display response from our greeting message before.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MessageController extends Controller
{
/**
* Show greetings
*
* @param Request $request [description]
* @return [type] [description]
*/
public function index(Request $request)
{
$data = [
‘message’ => trans(‘messages.greeting’)
];
return response()->json($data, 200);
}
}
Our controller is handling request and simply returning json data with translation greeting message.
Then we create our route and use localization middleware.
// Routes/api.php
Route::get(‘greeting’, ‘MessageController@index’)
->middleware(‘localization’);
Other Tips
Calling localization middleware in each route will become inefficient especially when our route is hundreds or more large. We can simply register middleware in group so we don not need to explicitly register in each route.
Open app/Http/Kernel.php again then edit array middlewareGroupsinside api:
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'api' => [
'throttle:60,1',
'localization'
'bindings',
],
];
Then our localization is works.
Let’s check our greeting API using postman. First we try with English (en)localization then Indonesian (id).
WARNING: The old mongo PHP driver is not supported anymore in versions >= 3.0.
Installation using composer:
composer require jenssegers/mongodb
And add the service provider in config/app.php(Laravel):
Jenssegers\Mongodb\MongodbServiceProvider::class,
For usage with Lumen, add the service provider in bootstrap/app.php. In this file, you will also need to enable Eloquent. You must however ensure that your call to $app->withEloquent(); is below where you have registered the MongodbServiceProvider:
The service provider will register a mongodb database extension with the original database manager. There is no need to register additional facades or objects. When using mongodb connections, Laravel will automatically provide you with the corresponding mongodb objects.
For usage outside Laravel, check out the Capsule manager and add:
In this new major release which supports the new mongodb PHP extension, we also moved the location of the Model class and replaced the MySQL model class with a trait.
Please change all Jenssegers\Mongodb\Model references to Jenssegers\Mongodb\Eloquent\Model either at the top of your model files, or your registered alias.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent {}
If you are using hybrid relations, your MySQL classes should now extend the original Eloquent model class Illuminate\Database\Eloquent\Model instead of the removed Jenssegers\Eloquent\Model. Instead use the new Jenssegers\Mongodb\Eloquent\HybridRelations trait. This should make things more clear as there is only one single model class in this package.
use Jenssegers\Mongodb\Eloquent\HybridRelations; class User extends Eloquent { use HybridRelations; protected $connection = 'mysql'; }
Embedded relations now return an Illuminate\Database\Eloquent\Collection rather than a custom Collection class. If you were using one of the special methods that were available, convert them to Collection operations.
$books = $user->books()->sortBy('title');
Configuration
Change your default database connection name in config/database.php:
This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent {}
Note that we did not tell Eloquent which collection to use for the User model. Just like the original Eloquent, the lower-case, plural name of the class will be used as the collection name unless another name is explicitly specified. You may specify a custom collection (alias for table) by defining a collection property on your model:
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent { protected $collection = 'users_collection'; }
NOTE: Eloquent will also assume that each collection has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class MyModel extends Eloquent { protected $connection = 'mongodb'; }
Everything else (should) work just like the original Eloquent model. Read more about the Eloquent on http://laravel.com/docs/eloquent
Optional: Alias
You may also register an alias for the MongoDB model by adding the following to the alias array in config/app.php:
This will allow you to use the registered alias like:
class MyModel extends Moloquent {}
Query Builder
The database driver plugs right into the original query builder. When using mongodb connections, you will be able to build fluent queries to perform database operations. For your convenience, there is a collection alias for table as well as some additional mongodb specific operators/operations.
All other (unsupported) operations are implemented as dummy
pass-through methods, because MongoDB does not use a predefined schema.
Read more about the schema builder on http://laravel.com/docs/schema
Geospatial indexes
Geospatial indexes are handy for querying location-based documents. They come in two forms: 2d and 2dsphere. Use the schema builder to add these to a collection.
To add a 2d index:
This service provider will slightly modify the internal
DatabaseReminderRepository to add support for MongoDB based password
reminders. If you don't use password reminders, you don't have to
register this service provider and everything else should work just
fine.
Queues
If you want to use MongoDB as your database backend, change the driver in config/queue.php:
You may also specify additional columns to update:
Soft deleting
When soft deleting a model, it is not actually removed from your
database. Instead, a deleted_at timestamp is set on the record. To
enable soft deletes for a model, apply the SoftDeletingTrait to the
model:
NOTE: you can also use the Laravel regexp
operations. These are a bit more flexible and will automatically convert
your regular expression string to a MongoDB\BSON\Regex object.
Eloquent allows you to work with Carbon/DateTime objects instead of
MongoDate objects. Internally, these dates will be converted to
MongoDate objects when saved to the database. If you wish to use this
functionality on non-default date fields, you will need to manually
specify them as described here: http://laravel.com/docs/eloquent#date-mutators
Example:
The belongsToMany relation will not use a pivot "table", but will push id's to a related_ids
attribute instead. This makes the second parameter for the
belongsToMany method useless. If you want to define custom keys for your
relation, set it to null:
If you want to embed models, rather than referencing them, you can use the embedsMany relation. This relation is similar to the hasMany relation, but embeds the models inside the parent object. REMEMBER: these relations return Eloquent collections, they don't return query builder objects!
You can access the embedded models through the dynamic property:
$books=User::first()->books;
The inverse relation is automagically available, you don't need to define this reverse relation.
$user=$book->user;
Inserting and updating embedded models works similar to the hasMany relation:
$book=newBook(['title'=>'A Game of Thrones']);$user=User::first();$book=$user->books()->save($book);// or$book=$user->books()->create(['title'=>'A Game of Thrones'])
You can update embedded models using their save method (available since release 2.0.0):
$book=$user->books()->first();$book->title='A Game of Thrones';$book->save();
You can remove an embedded model by using the destroy method on the relation, or the delete method on the model (available since release 2.0.0):
If you want to add or remove an embedded model, without touching the database, you can use the associate and dissociate methods. To eventually write the changes to the database, save the parent object:
$user->books()->associate($book);$user->save();
Like other relations, embedsMany assumes the local key of the
relationship based on the model name. You can override the default local
key by passing a second argument to the embedsMany method:
return$this->embedsMany('Book', 'local_key');
Embedded relations will return a Collection of embedded items instead
of a query builder. Check out the available operations here: https://laravel.com/docs/master/collections
EmbedsOne Relations
The embedsOne relation is similar to the embedsMany relation, but only embeds a single model.
If you're using a hybrid MongoDB and SQL setup, you're in luck! The
model will automatically return a MongoDB- or SQL-relation based on the
type of the related model. Of course, if you want this functionality to
work both ways, your SQL-models will need use the Jenssegers\Mongodb\Eloquent\HybridRelations trait. Note that this functionality only works for hasOne, hasMany and belongsTo relations.
Example SQL-based User model:
You can also perform raw expressions on the internal MongoCollection
object. If this is executed on the model class, it will return a
collection of models. If this is executed on the query builder, it will
return the original response.
// Returns a collection of User models.$models=User::raw(function($collection){return$collection->find();});// Returns the original MongoCursor.$cursor=DB::collection('users')->raw(function($collection){return$collection->find();});
Optional: if you don't pass a closure to the raw method, the internal MongoCollection object will be accessible:
By default, Laravel keeps a log in memory of all queries that have
been run for the current request. However, in some cases, such as when
inserting a large number of rows, this can cause the application to use
excess memory. To disable the log, you may use the disableQueryLog method: