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

问题描述 投票:0回答:1

我有一个名为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 model field backpack-for-laravel
1个回答
1
投票

正确的方法之一是使用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;
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.