Support Emojis in Laravel Application
How to store, read and update emojis in laravel application
Recently i was working in a project that require support for emojis to store and read it from database using inside a laravel application and in this short tutorials i will show you how to make this happen.
First: Make sure to change database collection to ( utf8mb4_unicode_ci
)
Second: In your database.php
config file, make sure to set the charset
and collation
to utf8mb4
:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
]
Third: Make sure to store emojis in string column
Some problem you may face
Specified key was too long error
As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php
file and inside the boot
method set a default string length:
use Illuminate\Support\Facades\Schema;
public function boot() {
Schema::defaultStringLength(191);
}
More Info Here
Final thoughts
This will make your string with emojis stored in unified format to replace it with images during view you can use one of this projects below inside laravel application or in front-end part of this application.
- https://github.com/unicodeveloper/laravel-emoji
- https://github.com/iamcal/js-emoji
- https://github.com/twitter/twemoji
Happy Coding π¨βπ»