Edit
Update an existing model
Controllers with any of these Traits have method update($id)
which a route can connect to for updating a model.
<?php
// ...
Route::put('/tasks/{id}', 'TaskController@update');
Validation
Method validationRules( ... )
is available for specifying the validation rules for the update($id)
method.
<?php
// ...
public function validationRules(array $data, $id = null) {
return [
'title' => "required|unique:tasks,title,$id,id"
];
}
Tips
- Parameter
$id
holds the id of the target model to update.- To use a different model apart from that provided by method
model()
, implementupdateModel()
to return the desired model.
Note
If the target model is not found, method
notFoundError()
is called which by default returns a 404 response.
Before update
To catch the model before it is updated, implement method beforeUpdate( ... )
.
<?php
//...
public function beforeUpdate(array &$data, Illuminate\Database\Eloquent\Model $model) {
// do something with/on $data and/or $model
}
Tip
- If the method returns a non-null value, the update process is terminated and the returned value is sent to the client as the response.
Before response
After the model has been updated, it can be accessed with the beforeUpdateResponse( ... )
method before it is sent to the client.
<?php
// ...
public function beforeUpdateResponse(Illuminate\Database\Eloquent\Model &$data) {
// do something with/on $data
}
Tip
If the method returns a non-null value, the returned value is sent to the client as the response.
Exceptions
Exceptions are caught in the update()
method and the update process is rolled back. To perform more operations when rolling back, implement method rollbackUpdate( ... )
.
<?php
// ...
public function rollbackUpdate(array $data, Illuminate\Database\Eloquent\Model $model) {
// do some further rolling back
}
Updated over 6 years ago