简体   繁体   中英

Using sync to detach in pivot table in Laravel

I have something strange happening which I can't understand and wondered if anyone could help me work out what's going on.

I have 2 tables (assessors, processes) and a pivot (process_assessor). I am trying to update the pivot with an assessor's processes so I have a form which when submitted is passed to this method...

public function updateProcesses( $id )
{
    $assessor = $this->model->find( $id );
    return $assessor->processes()->sync( $this->request->get( 'process_id' ) );
}

This works fine however when updating a user to have no processes I get an error message...

Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatSyncList() must be of the type array, null given, called

However, (and this is the weird bit) I also have a user profile module which uses exactly the same way to 'sync' with the pivot table however when I submit that form with all options for that particular module unchecked then it works, the user is detached from them in the pivot.

What am I doing wrong? Any ideas?

Simply cast to an array:

return $assessor->processes()->sync( (array) $this->request->get('process_id') );

Alternatively you can use empty array as a default value for get() :

return $assessor->processes()->sync( $this->request->get('process_id', []) );

however 1st option is more reliable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM