lundi 31 août 2015

Laravel Eloquent inserting relationship models

I'm trying to insert data into a pivot table using an Eloquent relationship model. I will try to explain below my current setup in the simplest terms.

I have 3 tables:

Users - this table is used to store users.

id    name    
1     John Smith
2     Fred Bloggs

UsersRoles - this table is a pivot table which is used to store the role a user has. A user may have multiple roles. The only role that we are interested in in this circumstance is the supervisor (which has a role_id of 2). The below example means that John Smith is a member of the supervisor role.

id    role_id    user_id
1     2          1
1     1          2

UserSupervisors - this table is the pivot table used to store supervisors that have been assigned to users. The below table shows that Fred Bloggs has John Smith as a supervisor.

id    user_id    supervisor_id
1     2          1

I have the following controller method which creates new users:

/**
 * Store a newly created resource in storage.
 *
 * @param  Request  $request
 * @return Response
 */
public function store(CreateUserRequest $request)
{
    // create user
    $user = $this->user->createUser($request->except('_token'));

    // create roles
    $this->user->createUserRoles(['user_id' => $user->id, 'role_id' => $this->user->findRoleByName('Contractor')->id]);

    // assign supervisors
    $this->user->assignContractorSupervisors($request->get('supervisors'));

    // send activation
    Event::fire(new UserCreated($user));

    return Redirect::back()->withMessage('New user created.');
}

The issue I am having is with assignContractorSupervisors(). This method calls a method within my repository which is below:

/**
 * Contractor supervisors.
 *
 * @return Object
 */
public function assignContractorSupervisors($request)
{
    return $this->user->contractorSupervisors()->insert($request);
}

The above method calls the belongsToMany method in my model:

/**
 * Supervisor belongs to many contractors.
 *
 * @return Object
 */
public function contractorSupervisors()
{
    return $this->belongsToMany('App\Models\User\ContractorSupervisors', 'contractor_supervisors', 'user_id', 'supervisor_id');
}

My problem is that the data gets inserted into the contractor_supervisors table but without a user_id, see below:

id    user_id    supervisor_id
1     0          1

How can I link up the user_id that was created by $user = $this->user->createUser($request->except('_token')); and insert this id into my pivot table?

Thanks in advance.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1KWESyT
via IFTTT

Aucun commentaire:

Enregistrer un commentaire