Anirudh Lou
Anirudh Lou

Reputation: 841

How to use update() functionality in Laravel?

Inside my store function i have to search a name of a particular person, thus:

$person = DB::select("select p.* from persons p where concat_ws(', ' ,p.family_name,concat_ws(' ',concat_ws(' ',p.first_name,p.middle_name),p.third_name)) like ?", [$request['person_name']]);

If this person exist i have to update the person and this one works:

Person::where('id', $person[0]->id)->update(['status' => 'Active']);

but not this one:

$person[0]->status = 'Active';
$pArray = json_decode(json_encode($person[0]), true);
$per = new Person($pArray);
$per->update();

Upvotes: 0

Views: 73

Answers (3)

Swati
Swati

Reputation: 496

Use your search query instead of mine. I think this will help you.

 $result = User::where('id', $userId)->first();
 $result->name = 'xyz';
 $result->update();

Upvotes: 1

matticustard
matticustard

Reputation: 5149

Since you have already created a new model instance, you would need to call the save() method.

$per = new Person($pArray);
$per->save();

Or, you can use update() to pass data into an existing model. But first, you need to retrieve the model you want to update.

$per = Person::find($pArray['id']);
$per->update($pArray);

Upvotes: 3

Rajdip Chauhan
Rajdip Chauhan

Reputation: 345

For update data in laravel using model you need to pass where condition in it.

Sample example

$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

Hope this helps you!

Upvotes: 0

Related Questions