错误:类stdClass的对象无法转换为字符串



我不明白我创建的代码出了什么问题

public function postRegister(Request $request) {
$admin = new SuperAdmin();
$admin->NIP = Input::get("NIP");
$admin->username = Input::get("username");
$admin->password = bcrypt(Input::get("password"));
$admin->nama_adm = Input::get("nama_adm");
$admin->no_hp = Input::get("no_hp");
$admin->role_id = DB::table('roles')->select('id')->where('namaRole', 'superadmin')->first();
$admin->save();
}

当我使用时

var_dump($admin);

结果:

object(AppSuperAdmin)#258 (27) { ["table":protected]=> string(10) "admin_role" ["fillable":protected]=> array(3) { [0]=> string(4) "name" [1]=> string(3) "NIP" [2]=> string(8) "password" } ["hidden":protected]=> array(2) { [0]=> string(8) "password" [1]=> string(14) "remember_token" } ["connection":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["keyType":protected]=> string(3) "int" ["incrementing"]=> bool(true) ["with":protected]=> array(0) { } ["withCount":protected]=> array(0) { } ["perPage":protected]=> int(15) ["exists"]=> bool(false) ["wasRecentlyCreated"]=> bool(false) ["attributes":protected]=> array(6) { ["NIP"]=> string(12) "092173092713" ["username"]=> string(5) "fazan" ["password"]=> string(60) "$2y$10$NRc7xG9VPIlmgN12gYPPF.W0vD/u7KmE/yzY5KzchyGG8xQBoJBDC" ["nama_adm"]=> string(3) "zan" ["no_hp"]=> string(9) "097123123" ["role_id"]=> object(stdClass)#268 (1) { ["id"]=> int(1) } } ["original":protected]=> array(0) { } ["changes":protected]=> array(0) { } ["casts":protected]=> array(0) { } ["classCastCache":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["dateFormat":protected]=> NULL ["appends":protected]=> array(0) { } ["dispatchesEvents":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["relations":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["timestamps"]=> bool(true) ["visible":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } } 

您正在将要创建的模型的属性role_id指定为对象(first()返回nullstdClass对象(:

$admin->role_id = DB::table('roles')->select('id')->where('namaRole', 'superadmin')->first();

您应该只传递角色的"id",而不是对象:

$admin->role_id = DB::table('roles')->where('namaRole', 'superAdmin')->value('id'),

此查询仅返回找到的第一条记录的id字段的值。

最新更新