Rafik malek Rafik malek - 18 days ago 6
MySQL Question

Laravel save() - inserting the data instead update

Want to updating the data using laravel. I make a function inside the model and using that method inside the controller but when calling the method its inserting the data with new id.function as following .

public function edit_client($req,$id) {
$client = new client();
$client->find($id);
$client->name = $req->name;
$client->address = $req->address;
$client->email = $req->email;
$client->phone = $req->phone;
$client->gender = $req->gender;
$client->department = $req->department;
$client->update();}

Answer

You can do this instead:

public function edit_client($req,$id) { 
    $client = Client::find($id); 
    $client->name = $req->name; 
    $client->address = $req->address; 
    $client->email = $req->email; 
    $client->phone = $req->phone; 
    $client->gender = $req->gender; 
    $client->department = $req->department; 
    $client->save();
}

Or use update() method:

public function edit_client($req,$id) { 
    $client = Client::where('id', $id)->update([
        'name' = $req->name,
        'address' = $req->address,
        'email' = $req->email,
        'phone' = $req->phone,
        'gender' = $req->gender,
        'department' = $req->department
    ]);
}

If you'll decide to use update() method, do not forget to add $fillable array.

Comments