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);
}
When using DB, a bool value is returned:
$user is a bool value.