0

How can I make a condition in update function which will check the value of collector_id and borrower_id is not equal to the other rows.

Here's what my table looks like

enter image description here

Here's my update function

public function update(Request $request, $id)
{

    $this->validate($request, [
        'collector_id' => 'required',
        'borrower_id' => 'required|unique:collector_members'
    ]);

    $requestData = $request->all();

    // dd($requestData);

    $collectormember = CollectorMember::findOrFail($id);
    $collectormember->update($requestData);

    return redirect('dashboard/collector-members')->with('flash_message', 'CollectorMember updated!');
}
SleepWalker
  • 613
  • 1
  • 12
  • 39
  • You mean that borrower_id and collector_id which you get through request does not match existing borrower_ids and collector_ids in table, that is they need to be unique? – N. Djokic Nov 13 '19 at 18:30
  • yes @N.Djokic let say in row 1 collector_id = 7 and borrower_id = 2, Then I should not be able to update that row with same values. – SleepWalker Nov 13 '19 at 18:50
  • Does this answer your question? [Laravel unique validation on multiple columns](https://stackoverflow.com/questions/50349775/laravel-unique-validation-on-multiple-columns) – miken32 Nov 13 '19 at 19:50
  • You should do this using [form request validation](https://laravel.com/docs/5.8/validation#form-request-validation) instead of inside your controller, or you will have to repeat this code for your `create` method as well. – miken32 Nov 13 '19 at 19:53

1 Answers1

1

You can add a rule like this.

$collectorId = $request->collector_id;
$borrowerId = $request->borrower_id;

$this->validate($request, [
    'collector_id' => 'required',
    'borrower_id' => [
        'required',
        Rule::unique('collector_members')->where(function ($query) use ($collectorId, $borrowerId) {
            return $query->where('collector_id', $collectorId)
                         ->where('borrower_id', $borrowerId);
        }),
    ],
]);
Vladan
  • 1,572
  • 10
  • 23