我正在开发一个API,我从移动应用程序获取表单数据到将其存储在数据库表$datetime = new DateTime('2017-01-20T13:59:19+03:00', new DateTimeZone('Asia/Kolkata'));
$new = $datetime->format('Y-m-d H:i:s e');
$arr = (explode(" ",$new));
$arr2 = explode(":",$arr[1]);
$arr3 = explode(":",$arr[2]);
$vicky = $arr2[0]+$arr3[0];
$arr2[0] = $vicky;
$finaltime = (implode(":",$arr2));
$final = $arr[0].' '.$finaltime;
echo $final;
中我希望在将数据存储到数据库之前修改列workers
数据
在我的控制器中我就像这样存储
registration_id
在我的模型中,我试图将public function store()
{
Driver::create(input::all());
return $this->respondCreated('Driver created successfully');
}
值更改为
registration_id
但它不能正常工作原始表单值插入数据库
如何将<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Driver extends Model
{
use SoftDeletes;
protected $fillable = [
'agent_id',
'registration_center',
'sponsor_name',
'event_name',
'registration_id',
];
protected $dates = ['deleted_at'];
public function modifyRegistrationId($registration_id)
{
$this->attributes['registration_id'] = 'test';
}
}
更改为其他值
期待急需的帮助
谢谢
答案 0 :(得分:1)
如果您始终覆盖该值define a mutator:
public function setRegistrationIdAttribute($value)
{
$this->attributes['registration_id'] = 'test';
}
如果您只想这样做一次,请覆盖以下值:
public function store(Request $request)
{
$request->registration_id = 'test';
Driver::create($request->all());
return $this->respondCreated('Driver created successfully');
}
答案 1 :(得分:1)
您可以在保存之前使用事件来更改任何数据。看看Laravel docs。这里我们使用boot()
定义回调行为:
class Driver extends Model
{
public static function boot()
{
parent::boot();
self::creating(function($model){
//before create, do this...
$lastRegistrationId = Driver::orderBy('id', 'desc')->first()->registration_id;
$this->registration_id = $lastRegistrationId.date('Y-m-d');
});
}
...
}
您可以使用的功能包括:创建,创建,更新,更新,保存,保存,删除,删除,恢复,恢复