Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent

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.

Last updated 2 years ago.
0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Lucassith lucassith Joined 8 Dec 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.