Home  >  Q&A  >  body text

Problems with writing data to associated tables when laravel uses DB classes

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);
    }
迷茫迷茫2687 days ago342

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-16 16:49:37

    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.

    reply
    0
  • Cancelreply