-
Notifications
You must be signed in to change notification settings - Fork 1
Dynamically forbid create update columns
macropay-solutions edited this page Aug 29, 2025
·
2 revisions
Both laravel-crud-wizard-free and maravel-rest-wizard can restrict create/update from controller at resource level or from the model at column level.
However, for external calls, there are some tricks for dynamically restrict columns create/update without defining the protected property on construct (which would mean useless work in most of the instantiations).
protected array $ignoreUpdateFor = [];
protected array $ignoreExternalCreateFor = [];
public function getIgnoreUpdateFor(): array
{
return $this->ignoreUpdateFor;
}
public function getIgnoreExternalCreateFor(): array
{
return (string)$this->getKeyName() === '' ?
$this->ignoreExternalCreateFor : \array_merge(
$this->ignoreExternalCreateFor,
\array_diff([$this->getKeyName()], $this->getFillable())
);
}You just have to declare these in your model:
public function getIgnoreUpdateFor(): array
{
if (...) {
return parent::getIgnoreUpdateFor();
}
return [...]; // your custom need.
}
public function getIgnoreExternalCreateFor(): array
if (...) {
return parent::getIgnoreExternalCreateFor();
}
return [...]; // your custom need.
}The controller will call these functions through the service and filter out the ignored columns before passing the payload to the service.
- Another way would be to dynamically define the validateCreateRequest/validateUpdateRequest functions in your controller:
/**
* @throws \Throwable
*/
protected function validateCreateRequest(Request $request): array
{
if (...) {
// return ...;
}
// return ...;
}
/**
* @throws \Throwable
*/
protected function validateUpdateRequest(Request $request): array
{
if (...) {
// return ...;
}
// return ...;
}The controller will use only the validated data for create/update.
Notes:
- both libs support upsert for resources that don’t have auto-increment primary keys. The controller update will call the controller’s create function if the model is not found and if:
/**
* @throws \Exception
*/
public function isUpdateOrCreateAble(array $requestBody = []): bool
{
if ($this->model->incrementing) {
return false;
}
foreach ($this->model->getPrimaryKeyFilter() as $column => $value) {
if (!\is_array($value) && \is_string($column)) {
if (!\array_key_exists($column, $requestBody)) {
return false;
}
continue;
}
if (!\array_key_exists(\reset($value), $requestBody)) {
return false;
}
}
return true;
}- maravel-rest-wizard supports also increments/decrements via api.