如何在保存前根据其他字段值设置一个字段的值
How to set the value of a field based on other field values before save
我有一个名为 students 的 table,它有 first_name、last_name 和 full_name 列。我希望在将值保存到数据库之前使用 first_name .' '. last_name
设置 full_name 的值。
public function store(StoreRequest $request)
是最好的地方吗?需要什么代码?
$this->crud->addField([
'name' => 'first_name',
'type' => 'text',
'label' => "First Name",
'tab' => 'Details'
]);
$this->crud->addField([
'name' => 'last_name',
'type' => 'text',
'label' => "Last Name",
'tab' => 'Details'
]);
$this->crud->addField([
'name' => 'full_name',
'type' => 'text',
]);
// add asterisk for fields that are required in StudentRequest
$this->crud->setRequiredFields(StoreRequest::class, 'create');
$this->crud->setRequiredFields(UpdateRequest::class, 'edit');
$this->crud->allowAccess('show');
}
public function store(StoreRequest $request)
{
// your additional operations before save here
$redirect_location = parent::storeCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
谢谢。
正确的方法之一是使用 laravel eloquent 模型事件。
您可以使用Student
模型的creating
事件。 creating
事件发生在模型保存到数据库之前。
可以在AppServiceProvider
boot
函数中绑定学生模型的创建事件
AppServiceProvider
use App\Models\Student;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Student::creating(function ($student) {
$student->full_name = $student->first_name.' '.$student->last_name;
});
}
}
我有一个名为 students 的 table,它有 first_name、last_name 和 full_name 列。我希望在将值保存到数据库之前使用 first_name .' '. last_name
设置 full_name 的值。
public function store(StoreRequest $request)
是最好的地方吗?需要什么代码?
$this->crud->addField([
'name' => 'first_name',
'type' => 'text',
'label' => "First Name",
'tab' => 'Details'
]);
$this->crud->addField([
'name' => 'last_name',
'type' => 'text',
'label' => "Last Name",
'tab' => 'Details'
]);
$this->crud->addField([
'name' => 'full_name',
'type' => 'text',
]);
// add asterisk for fields that are required in StudentRequest
$this->crud->setRequiredFields(StoreRequest::class, 'create');
$this->crud->setRequiredFields(UpdateRequest::class, 'edit');
$this->crud->allowAccess('show');
}
public function store(StoreRequest $request)
{
// your additional operations before save here
$redirect_location = parent::storeCrud($request);
// your additional operations after save here
// use $this->data['entry'] or $this->crud->entry
return $redirect_location;
}
谢谢。
正确的方法之一是使用 laravel eloquent 模型事件。
您可以使用Student
模型的creating
事件。 creating
事件发生在模型保存到数据库之前。
可以在AppServiceProvider
boot
函数中绑定学生模型的创建事件
AppServiceProvider
use App\Models\Student;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Student::creating(function ($student) {
$student->full_name = $student->first_name.' '.$student->last_name;
});
}
}