How update fields in Lumen - laravel

I want to update few fields in my table. How it is update query write in lumen. I want to update salutation, name, lastname, address fields with dynamicaly equal to id.
$query = "UPDATEpassengersSETname= ? WHERE (id='1') ";
$update = app('db')->update($query, [$passenger->name,]);
I want to pass id value as dynamically.

Use the update() method with where():
DB::table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);

Use update
DB::table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);
$update = app('db')->table('passengers')->where('id', $id)->update(['name' => $name, 'lasname' => $lastname]);

Related

Laravel increment column in updateOrCreate and get the model

I am trying to increment a column and updateorcreate a record in one query by doing so:
$model = Model::updateOrCreate([
'email' => $email
], ['received_at' => $received_at])->incremet('received_count');
This does the job as I wanted it too. It updates or create a record and increments the received_count column.
But after the query, I wanted to get the updated/created row, but when I log $model, it only logs 0 or 1. I can confirm that this is because of the ->increment().
But to be honest, I don't know any way how to increment the received_count column other than how I currently did it.
How do I achieve so that it updates or create a record, at the same time increments the received_count column, and after all of this, returns the updated/created object?
As much as posssible, I want this all in one query. Getting the model should be a memory.
$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);
$model->increment('received_count');
$model->refresh(); // this will refresh all information for your model.
or you can simply:
$model = Model::updateOrCreate(['email' => $email], ['received_at' => $received_at]);
tap($model)->increment('id'); // this will return refreshed model.
just fresh model after incremet:
$model = Model::updateOrCreate([
'email' => $email
], ['received_at' => $received_at]);
$model->incremet('received_count');
$model->fresh();

updateOrCreate isn't filling all the fields in Laravel 5.6

I have a code:-
$tokenUpdated = AppToken::updateOrCreate(
array(
'user_id' => $user_id, 'token' => $token),
array('expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at)
);
Though new rows are being inserted, the expiry, created_date fields values aren't getting saved. They records show NULL value which are default values.
What am I doing wrong?
First you need to check if expiry and created_date are returning values, if so then you could use the updateOrCreate function like this:
$tokenUpdated = AppToken::updateOrCreate(
['user_id' => $user_id, 'token' => $token]
['expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at
]
);
check laravel eloquent documentation: https://laravel.com/docs/5.6/eloquent

Laravel Update Multiple Columns with QueryBuilder

I'm using Query builder, I successfully update na first column but on the second query the change doesnt happen, I already checked the view part the name of input and its correct. here is my code.
DB::table('area')
->where('id', $request->get('area_id'))
->update(['island_group_id' => $request->get('island_group_id')],
['region_id' => $request->get('region_id')]);
return 'test';
$updateDetails = [
'island_group_id' => $request->get('island_group_id'),
'region_id' => $request->get('region_id')
];
DB::table('area')
->where('id', $request->get('area_id'))
->update($updateDetails);
DB::table('area')
->where('id', $request->get('area_id'))
->update([
'island_group_id' => $request->get('island_group_id'),
'region_id' => $request->get('region_id')
]);
return 'test';
I think it will be helpful to you.
$area_id = $request->get('area_id');
$island_group_id = $request->get('island_group_id');
$region_id = $request->get('region_id');
$update_details = array(
'island_group_id' => $island_group_id
'region_id' => $region_id
);
DB::table('area')
->where('id', $area_id)
->update($update_details);
Because you use every time new array for update field. Please use one array for update multiple field like:
DB::table('area')
->where('id', $request->get('area_id'))
->update(array(
'island_group_id'=>$request->get('island_group_id'),
'region_id'=>$request->get('region_id')
));

How to add unique validation on combination of firstname and lastname in laravel5?

I need to validate user table in which not repeated combination of (firstname and lastname). for example:- firstname=dc lastname=patel already exist in table. i need to prevent same entry next time.
Finally I have perfect solution for this.
$validationRule = ['first_name' => 'required','last_name'=>'required'];
$validationMsg = ['first_name.required' => 'First Name is required', 'last_name.required' => 'Last Name is required'];
$validation = Validator::make(['first_name' => $firstName, 'last_name' => $lastName], $validationRule, $validationMsg);
$validation->after(function ($validation) use ($firstName, $lastName) {
$checkName = User::where('first_name', $firstName)->where('last_name', $lastName)->get();
if (count($checkName) > 0) {
$validation->errors()->add('first_name', 'User already exists, please enter another user.');
}
});
if ($validation->fails()) {
foreach ($validation->errors()->all() as $error) {
$message = $error;
}
return response(\Helpers::makeAjaxResponse(false, $message));
} else {
//Save record code here
}
You can use something simular to composite UNIQUE key in table if database provide this possibility.
http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html
with using laravel unique validation rule
how can you allow users with same lastname but not firstname for registeration?
unique.firstname
First check records count with the given firstname and lastname.
If the count is '0' save the record or else show message.
Here is some code hint
$users = DB::table('users')
->where(['firstname' => 'dc', 'lastname' => 'patel'])
->count();
if($users === 0) {
// save the record.
} else {
// Show message
}
Since Laravel 5.5 you can use elegant Rule class like:
use Illuminate\Validation\Rule;
// ...
$firstNameUniqueRule = Rule::unique('users')->where('last_name', request()->get('last_name', ''));
$rules = [
'first_name' => ['required', $firstNameUniqueRule],
'last_name' => 'required',
];

Eloquent update and limit

I could not figure out how can i use both update and limit methods in laravel eloquent orm.
$affectedRows = Promo::where('used','=',0)
->update(array('user_id' => Auth::user()->id))
->limit(1); // Call to a member function limit() on a non-object
//->take(1); // Call to a member function take() on a non-object
I tried both limit and take methods.
I want to do only one result will be update.
But i think, i can not use limit or take methods on update.
Is there any way to update only one row via eloquent?
Add :
Eloquent ORM
$affectedRows = Promo::where('user_id','=',DB::raw('null'))->take(1)
->update(
array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
)
);
Query Builder
$affectedRows = DB::table('promos')->whereNull('user_id')
->take(1)
->update(array(
'user_id' => Auth::user()->id,
'created_ip' =>Request::getClientIp(),
'created_at' => new DateTime,
'updated_at' => new DateTime
));
These two codes did not add limit param to the query
Output:
update `promos` set `user_id` = '1', `created_ip` = '127.0.0.1', `created_at` = '2013-06-04 14:09:53', `updated_at` = '2013-06-04 14:09:53' where `user_id` = null
Talking about laravel 5 (not sure about L4), depends on db engine.
MySQL supports limit for update so it works, here is the laravel code that do that:
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Query/Grammars/MySqlGrammar.php#L129
so, first ->limit(1) and then ->update([fields]);
DB::table('table')
->where('field', 'value')
->limit(1)
->update(['field', 'new value']);
I used raw query. There is no method limit/take for update and delete queries on both eloquent and query builder. Use
DB::update(DB::raw("UPDATE query"));
like this.
I have not tried it but the Laravel 4 logic makes me think this syntax would work :
$affectedRows = Promo::where('used','=',0)
->limit(1)
->update(array('user_id' => Auth::user()->id));

Resources