dongyong5255
2015-07-12 21:09
浏览 149
已采纳

laravel 5.1从mysql返回乱码

I am new to laravel framework. I am using Homestead as my development environment and everything works fine. The problem is that I insert Persian language records into mysql database and when I return them in some views, the Persian charecters gets garbled (e.g "آذرشهر" returned as "\u0622\u0630\u0631\u0634\u0647\u0631"). Before using laravel I had a simillar problem which was solved using mysqli_set_charset. my old code was this:

class MySQLDatabase {
      private  $connection;
      public function __construct(){
            $this->openConnection();
            mysqli_set_charset($this->connection, 'utf8');
      }
      public function openConnection(){
            $this->connection=mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

            if(mysqli_connect_errno()){
                  die("Database connection failed:" .
                        mysqli_connect_error().
                        "(". mysqli_connect_errno().")"
                  );
            }
      }

My laravel database config file is like this:

'default' => env('DB_CONNECTION', 'mysql'),
'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

and the .env file is like this:

APP_ENV=local
APP_DEBUG=true
APP_KEY=XXXXXXXX

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

How can I fix this problem?

This is a view:

 @extends('app')

    @section('content')
            <h1>شهر</h1>
            @foreach($cities as $city)
            {{ $city }}
            @endforeach
    @stop

and the resulting object is like this:

{"id":402,"city":"\u0622\u0630\u0631\u0634\u0647\u0631","province_id":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsjmrpym220113739 2015-07-13 04:04
    已采纳

    In fact this has nothing with Laravel. The problem was that I tried to return a whole object (i.e. {{$city}}) to my view while I should return the city name like this: {{$city->city}}

    点赞 评论

相关推荐 更多相似问题