laravel/framework — pull request #4442 by Xethron (2014-05-19 12:19:42+00:00)
Title: Add ability to set pivot filters on save

This adds the ability to setup "filters" in your model, and save those column/value pairs when links are created.

I am working on a Legacy system, that has filters set in the pivot table (Job description), and I had to filter by them, as well as create links with them.

We also have a very complicated way of working with id's, as we do not have AI fields.

This is how I ended up using it in my model...

```php
belongsToManyEmployees('DEVELOPERS');
}

public function secretaries()
{
return $this->belongsToManyEmployees('SECRETARY');
}

public function managers()
{
return $this->belongsToManyEmployees('MANAGER');
}

public function drivers()
{
return $this->belongsToManyEmployees('DRIVER');
}

protected function belongsToManyEmployees($job)
{
return $this->belongsToMany('Employee')
->filter('job', $job)
->setFilter(function($pivot) {
$branch_id = $pivot->getParent()->branch_id;
$max = DB::table($pivot->getTable())->
where('branch_id', $branch_id)->
first([DB::raw('MAX(`link_id`) as max')]);

$result['branch_id'] = $branch_id;
$result['link_id'] = $max ? $max->max+1 : 1;
return $result;
});
}
}
```

Outside of the model, you can now use:

$employer->developers()->save($employee);

This will set the `job` field to DEVELOPER as well as set the branch_id and link_id fields.