JohnSmith
JohnSmith

Reputation: 141

Laravel Many To Many Update Specific Field

I have many to many relationship. In postman I pass find_id and status.

My query is like: UPDATE finds_user SET status = TRUE WHERE find_id = 2 AND user_id = 1.

I do it now like that:

DB::table('finds_user')
    ->where('find_id', '=', $request->find_id)
    ->where('user_id', '=', $user->id)
    ->update(['status' => $request->status]);

How I can do it with Eloquent instead of DB Query Builder?

Thank you a lot!

Upvotes: 1

Views: 153

Answers (1)

OMR
OMR

Reputation: 12188

we have tow condition for update:

1- find_id = 2

2- user_id = 1.

suppose the relation name in the user model called 'finds' the query will look like this:

User::find(1)->finds()->newPivotQuery()->where('find_id',2)->update(['status'=>true])

and if you have a model for the pivot table with name like "FindUser":

FindUser::where('user_id',$user->id)->where('find_id',2)->update(['status'=>true]);

Upvotes: 1

Related Questions