Hello.
I want to seed my database with users that have specific roles for every website. To do that I use query to find all users with user_id and role_id where website_id = null. Here is how my tables look like
USERS
user_id
user_name
ROLES
role_id
role_name
WEBSITES
website_id
website_name
USER_WEBSITE
user_id
website_id (nullable)
role_id
User model:
public function website()
{
return $this->belongsToMany('App\Website');
}
How can I insert null into the pivot table USER_WEBSITE?
I have tried this
$user=App\User::first();
$role=App\Role::first();
$user->website()->attach(null, array('role_id' => $role->id));
After I proceed with the seeding the table, it remains is empty.
Am I doing something wrong or it is not the proper way to insert values? There is no error message.
If I enter website_id number instead of null there will be a one record as expected.
Referring to this ( http://laravel.io/forum/06-29-2014-custom-pivot-table-that-accepts-null-values-using-attach-does-not-work-with-null-values-why-how-to-work-around ) problem, you can pass null only in square brackets.
So the solution is
$user=App\User::first();
$role=App\Role::first();
$user->website()->attach([null], array('role_id' => $role->id));
It actually works.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community