Search code examples
phplaravelsyntax-errorstdclass

Error : Object of class stdClass could not be converted to string


I don't understand what's wrong with the code I created

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();
}

when I'm using

var_dump($admin);

the result :

object(App\SuperAdmin)#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) "*" } } 

Solution

  • You are assigning an attribute, role_id, of the model that you are creating as an object (first() returns null or a stdClass object):

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

    You should only be passing the 'id' of the Role not an object:

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

    This query only returns the value of the id field of the first record found.