若是其餘語言沒有定義,會默認的查找en下的定義php
resources/lang
下建立須要的語言文件夾,如jp,默認是en。而後建立語言包文件前端
trans.php
json
return [
//User
'user_name_required' => 'User name cannot be empty',
'user_name_between' => 'User name length 5-10 characters',
'user_name_unique' => 'User names must be unique',
'user_password_required' => 'Password cannot be empty',
'user_password_between' => 'Password length 5-10 characters',
'user_role_required' => 'Role cannot be empty',
//Role
'role_name_required' => 'Role name cannot be empty',
'role_name_unique' => 'Role names must be unique',
// DbException
2000 => 'Database operation exception',
2001 => 'Database insert failure',
2002 => 'Database update failure',
2003 => 'Database delete failure',
];
複製代碼
經過前端頭的X-Language,來判斷是什麼語言,並設置語言bash
SwitchLanguage.php
app
class SwitchLanguage
{
public function handle($request, Closure $next)
{
$lang = $_SERVER['HTTP_X_LANGUAGE'] ?? 'jp';
app()->setLocale($lang);
return $next($request);
}
}
複製代碼
註冊路由中間件ui
Kernel.php
this
'lang' => \App\Http\Middleware\SwitchLanguage::class,
複製代碼
路由使用中間件spa
Route::middleware( 'lang')->group(function () {
});
複製代碼
自定義異常能夠經過異常碼進行判斷code
BaseException.php
中間件
public function __construct($code = 0, $message = '', $httpCode = 0, Throwable $previous = null)
{
$this->default_code = $code == 0 ? $this->default_code : $code;
$this->default_message = empty($message) ? trans("trans.$this->default_code") : $message;
$this->default_httpCode = $httpCode == 0 ? $this->default_httpCode : $httpCode;
parent::__construct($message, $code, $previous);
}
複製代碼
Handler.php
if ($exception instanceof ValidationException) {
$message = $exception->validator->errors()->first();
return response()->json([
'code' => 1000,
'message' => trans("trans.$message"),
], 422);
}
複製代碼
UserRequest.php
public function messages()
{
return [
'name.required' => 'user_name_required',
'name.between' => 'user_name_between',
'name.unique' => 'user_name_unique',
'password.required' => 'user_password_required',
'password.between' => 'user_password_between',
'role.required' => 'user_role_required',
];
}
複製代碼