我有一个名为students的表,其中包含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模型事件。
您可以使用creating
模型的Student
事件。 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;
});
}
}