我有一个多语言(英语和西班牙语)Laravel 应用程序,其中集成了用于多语言内容的 Spatie\Translatable 和用于基于角色/权限的用户授权的 Spatie\Permission。
一切都按预期工作,但是当我尝试为角色(或权限)名称使用多语言内容时,数据不是根据区域设置来的。我总是得到 JSON 字符串。
实际用例:- 我想显示分配给他们的角色和权限(根据区域设置)的用户列表。默认情况下, Spatie\Permission 包为权限和角色表创建 id、name、guard name 字段。因此,我为可翻译创建了一个新字段 custom_name。因为我不能使用 name 字段作为可翻译,因为角色(或权限)名称字符串(例如,manager)用于中间件或 @can 运算符。喜欢
web.php
Route::group(['middleware' => ['permission:manage sales']], function () {
// route for user who can have manage sales permission.
});
Route::group(['middleware' => ['role:manager']], function () {
// routes
});
?>
User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use App;
use App\Role;
use App\Interfaces\CommonConstants;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail, CommonConstants
{
use Notifiable, HasRoles, SoftDeletes, HasApiTokens;
/*
* Get the role of the user.
*/
public function role()
{
return $this->roles ? $this->roles->first() : null;
}
}
?>
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Spatie\Permission\Models\Role as RoleModel;
class Role extends RoleModel
{
use HasTranslations;
public $timestamps = true;
public $translatable = ['custom_name'];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::deleted(function($role) {
$role->permissions()->each(function($permission) {
$permission->delete();
});
});
}
}
?>
UserController.php
<?php
namespace App\Http\Controllers;
use App\Role;
class UserController extends Controller implements CommonConstants
{
/**
* get user info
*
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
$user = $request->user();
echo "<pre>";
print_r(Role::find(1)->custom_name); # it will give the custom_name according to locale.
print_r($user->role()->custom_name); # it return json object.
die;
}
}
?>
输出
<块引用>Gerente {"en":"Manager", "es":"Gerente"} // 如果是西班牙语
Manager {"en":"Manager", "es":"Gerente"} // 如果是英文
我认为问题出在角色对象上。当我们使用 Role 模型(即 Role::find(1) 获取角色时,它将返回“App\Role Object”类型的对象,当我像 $user->role() 这样从用户获取角色时,它将返回返回“Spatie\Permission\Models\Role Object”类型的对象。
如此可翻译的概念不适用于“Spatie\Permission\Models\Role Object”对象。