Saturday, March 11, 2017

eloquent: check for existing data in pivot table (primary key + extra column)

I have a pivot table with an extra column. I need to check if pair of data exists in this table prior to updating the extra column. There are two orders of problems here, first how can I do this check?

I tried something like

If ($user->pivot_table->contains($key, '&&', $extra_column)){}

to no avail.

Second, how do you update the extra column in the pivot ?

/// this what worked for me:

$user = Auth::user();

$key = $request->input('key');
$extra_column = $request->input('extra_column');

    if (count($user->groups()->where('key', $key)->where('extra_column', $extra_column)->first())){

        // fails (data exists already)

    }else{

        //update pivot
$user->groups()->updateExistingPivot($key, ['extra_column' => $extra_column]);

    }



via Chriz74

Advertisement