Reputation: 2233
I have a table where i have user_id
and role_id
in it. Now if I select user_id =1 from dropdown and role_id = 2 from dropdown and save it ..Next time if I want to set same user another role instead of creating new row in table..How to update it without creating new one? can anyone suggest something?
$roleUser = RoleUser::firstOrNew(
['role_id' => $request->Input(['role_id']),
'user_id' =>$request->Input(['user_id'])] );
$roleUser->save();
I used the firstOrNew method but it creates a new entry instead of updating the old one.
Upvotes: 0
Views: 7458
Reputation: 8308
so where's the issue here?
you are using firstOrNew
method , which is similar to firstOrCreate
typically do the following:
Select from the database
and if not exists
insert the given data
in case of using firstOrNew , you will need to ->save()
to execute the query .
so it will not update your data if exists .
however, I think that you are looking for updateOrCreate
method, which is take two array arguments , the first is the inserted data , and if exists the function takes the two array argument to update your row.
You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():
$roleUser = RoleUser::updateOrCreate(
// if not exists, insert the following RoleUser data
['role_id' => $request->Input(['role_id']),'user_id' =>$request->Input(['user_id'])],
// otherwise, update RoleUser set role_id = ?
['role_id' => $request->Input(['role_id'])]
);
Upvotes: 1
Reputation: 318
$roleUser = RoleUser::firstOrNew(array('role_id' => Input::get('role_id')));
$roleUser ->save();
you can add multiple fields..
example..
If there's a flight from Oakland to San Diego, set the price to $99. If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
`
Upvotes: 0
Reputation: 3009
I'm using this source code when Update or Create new record. Worked well with Laravel 5.2
If exist one record have user_id
== your user_id
=> Will update role_id
Else will insert one more record for your user_id
$roleUser = RoleUser::updateOrCreate([
'user_id' => $request['user_id'],
],
[
'role_id' => $request['role_id'],
]);
Upvotes: 3
Reputation: 16364
Here is a code that should work. However, I don't quite understand your database architecture choice. If a user can only have one role, why don't you define a role_id
in your users
table, and then use a belongsTo
relationship?
$role_user = RoleUser::where('role_id',$request->get('role_id'))
->where('user_id',$request->get('user_id'))
->first();
if (is_null($role_user)) {
RoleUser::create([
'user_id' => $request->get('user_id'),
'role_id' => $request->get('role_id')
])
}
Upvotes: 1