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.
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'],
]);
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')
])
}
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'])]
);
$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]
);
`
Related
I want to use this code: Model::update($request);, However all fields in the table might be modified by a malicious user so I change the $fillable in the model to modify only the ones that user can modify not others. But now the problem is that I can't modify it myself by own values.
id name verified
1 Alex 0
if the data the malicious user sends inside $request is:
[
'name' => 'ModifiedAlex',
'verified' => 1,
]
so it will modify the table and get verified that is not good And when setting $fillable to only name:
$fillable = [
'name'
];
then I myself can't modify that with Model::where('id', $userId)->update(['verified' => 1]).
What to do then? Use $fillable or not?
Keep using fillable and eloquent for the malicious users.
You can use Query Builder to avoid the fillable for yourself. It doesn't check the fillable.:
DB::table('users')->where('id', $userId)->update(['verified' => 1]); // update with verified.
You can update records by object
$user = \App\User::find(1);
$user->verified = 1;
$user->save();
Where user is giving data you can use Model::where('id', $userId)->update($request->except('_token')) so it avoids any other fields.
$request->except('_token') gives you all the post data except the _token index
But for admin you can use save on object to update / create users
I am using the updateOrCreate() function to update the record if a record is already available in the table based on some condition. However, I do not want to update one of my columns that contains a unique value.
I want to perform the same action to this column like created_at is working
while creating the records value is adding to the created_at column but while updating it contains the same.
To prevent this issue I removed that column name from $fillable in my model. But, in this case, it is not adding any value to this column.
protected $fillable = ['uid', 'channel', 'updated_at'];
$data = [
'uid' => Helper::generateUid(),
'channel' => $info['channel'],
'created_at' => time(),
'updated_at' => time(),
];
$cond = ['channel' => $info['channel']];
$isAdded = Templates::updateOrCreate($cond, $data);
Expected result
I don't want to update uid column if details already there.
Actual result
If details are not there it adds value to uid column and other columns also and if details are available then also it is updating uid column.
You can't do that with the updateOrCreate method. You'll need to be slightly more explicit. You can use the firstOrNew method to retrieve or instantiate a new object. And then you can use the exists property to determine if it is an existing or new object.
$template = Templates::firstOrNew(['channel' => $info['channel']]);
if (!$template->exists) {
$template->uid = Helper::generateUid();
}
$template->save();
I left out the created_at and updated_at fields because they are automatically handled by Laravel.
I'm trying to create multi selection bootstrap output to save in database but I'm getting an array in my controller like ["6","7"]. How I can save this?
There is 2 selection that means 2 row must created.
The query I was trying:
$table = Pool_user::updateOrInsert(['pool_id' => [$string1], 'user_id' => $request['id']]);
Can anyone help me to solve this?
By responding directly to your question, you need to create an array of arrays with the values you want to enter.
Something like this:
$array = [];
foreach($request['pool_ids'] as $pool_id){ //$request['pool_ids'] -> ["6","7"]
array_push($array, [
'pool_id' => $pool_id,
'user_id' => $request['id']
]);
}
$table = Pool_user::insert($array);
However, considering that Pool_user is a Pivot table of a Many to Many relationship, there is a much better method of doing this.
Let's say in User Model, have a relationship called polls().
You can simply ask the Eloquent to synchronize the relationships:
$user = User::find($request['id']);
$user->polls()->sync($request['pool_ids']); //$request['pool_ids'] -> ["6","7"]
Hope this helps
Is there a way to map field names to a database to a different attribute name in the model? For example, if the database has a field name of customer_id but I wanted to use eloquent in this way Customer::get(['id']) I've tried using the getAttribute method but that is called after eloquent has attempted to get the value.
You can use accessors to work with such attributes, but there's no way to query them this way with core eloquent.
But fear not! Use this package https://github.com/jarektkaczyk/eloquence and you can easily achieve what you want (Mappable in particular):
// Customer model
protected $maps =[
'id' => 'customer_id',
'name' => 'customer_name',
...
];
// then you can do this:
$customer = Customer::where('name', 'whatever')->first();
// calls WHERE customer_name = ? sql
$customer->id; // customer_id column
$customer->name; // customer_name column
$customer->name = 'different name'; // set mutator works as well
It's in heavy development and currently select is not yet supported, but it's matter of day or two. select support has been pushed already.
I have the following basic schema:
players
id
name
profiles
id
player_id
email
subsets
id
profile_id
alias
I was under the impression the following operation was possible when creating a new record:
Player::create([
'name' => 'Player 1',
'profile.email' => 'player1#email.com',
'profile.subset.alias' => 'Player 1 alias'
]);
Since this code doesn't seem to work, is there anyway to save relationships records together with the create method?
Basically, you can't do this as easy as it looks.
In the docs, all related models are created after the base model is created
$profile = new Profile(array('email' => 'player1#email.com','alias'=>'Player 1 alias'));
$player = new Player(array('name'=>'Player 1'));
$player = $post->profile()->save($profile);
However , if you really want to do it in one go, you can overwrite the save() method in the Player model :
public function save(){
Database::transaction(function() {
$profileModel = new Profile($this->profile);
parent::save();
$this->profile()->insert($profileModel);
});
}
You will then pass the array to the Player method like :
array(
name='Player name',
profile=>array(
email=>'player1#email.com',
subset=>array(
alias=>'Player 1 alias'
)
);
Although this is not a recommended action.
Please read more about how to save the Eloquent models and relationships :
Tutorial 1
Tutorial 2
Everywhere is suggested to create the base model first, then the related models.