首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在保存前根据其他字段值设置字段的值

如何在保存前根据其他字段值设置字段的值
EN

Stack Overflow用户
提问于 2019-04-11 08:11:24
回答 1查看 565关注 0票数 0

我有一个名为students的表,其中包含first_name、last_name和full_name列。我希望在将值保存到数据库之前使用first_name .' '. last_name设置full_name的值。

public function store(StoreRequest $request)是最好的地方吗?需要什么代码?

代码语言:javascript
复制
        $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;
    }

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-11 09:23:51

要做到这一点,正确的方法之一是使用laravel雄辩的模型事件。

您可以使用Student模型的creating事件。creating事件恰好在将模型保存到数据库之前发生。

您可以在AppServiceProvider boot函数中绑定学生模型的创建事件

AppServiceProvider

代码语言:javascript
复制
use App\Models\Student;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        Student::creating(function ($student) {
            $student->full_name = $student->first_name.' '.$student->last_name;
        });
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55622944

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档