Problems with writing data to associated tables when laravel uses DB classes
迷茫
迷茫 2017-05-16 16:47:37
0
1
397

Problems with writing data to associated tables when laravel uses the DB class:

When using the facade, to set roles for the current user, you can use $user->roles()->attach(1); as shown below:

    public function run()
    {
        $user=User::create([
            'name' => 'xiaoming',
            'email' => 'xiaoming@example.com',
            'password' => bcrypt('secret'),
            
        ]);
        $user->roles()->attach(1);
    }

Problem:
Now we need to use the DB class to complete the above functions, the $user->roles()->attach(1); of the following code cannot Run,
will report an error:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function roles() on boolean

How should I write it?

    public function run()
    {
        $user=DB::table('users')->insert([
            'name' => 'xiaoming',
            'email' => 'xiaoming@example.com',
            'password' => bcrypt('secret'),
        ]);
        $user->roles()->attach(1);
    }
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
黄舟

When using DB, a bool value is returned:

$user=DB::table('users')->insert([
            'name' => 'xiaoming',
            'email' => 'xiaoming@example.com',
            'password' => bcrypt('secret'),
        ]);
$user->roles()->attach(1);

$user is a bool value.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template