在Laravel 5.1中将模型保存到数据库之前,请执行一些操作
在将数据写入Laravel 5.1模型中的数据库之前,如何修改某些数据字段或进行更多验证? 关于该问题的文档很难在实际应用中使用: 我的代码是在Laravel 5.1中将模型保存到数据库之前,请执行一些操作,laravel,laravel-5,Laravel,Laravel 5,在将数据写入Laravel 5.1模型中的数据库之前,如何修改某些数据字段或进行更多验证? 关于该问题的文档很难在实际应用中使用: 我的代码是 <?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Helpers\Tools as Tools; class Atoken extends Model { /** * The database table used by the mode
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;
class Atoken extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'atoken';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'token',
'user_id',
'role',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
];
public static function newToken($userId, $role){
# Remove all token assoiciate with input user;
Atoken::where('user_id', $userId)->delete();
$params = [
'user_id' => $userId,
'role' => $role,
];
Atoken::insert($params);
$item = Atoken::where('user_id', $userId)->first();
return $item->token;
}
protected static function boot(){
static::creating(function ($model) {
$model->token = 'sometoken';
});
}
}
我怎样才能解决它呢?课堂午餐扩展得很有说服力
{
受保护的静态函数启动()
{
静态::创建(函数($model){
$model->topping='Butter';
返回$model->validate();
});
}
受保护函数验证()
{
//显然,在这里做真正的验证:)
返回rand(0,1)?true:false;
}
公共静态函数newToken($userId,$role)
{
静态::其中('user_id',$userId)->delete();
返回静态::创建([
'user_id'=>$userId,
“角色”=>$role,
])->代币;
}
}
我建议进入EventServiceProvider并注册事件侦听器
public function boot(DispatcherContract $events)
{
parent::boot($events);
// Register Event Listeners
\App\Product::updating(function ($product) {
$product->onUpdating();
});
...
然后在模型中创建函数onUpdate
。您还可以从保存、保存、创建、创建、更新、更新..
本文档包含更多内容:
我已经显示了我的代码。它似乎与您的代码非常接近,但不起作用。@ronin1184-
Atoken::insert($params)
不使用该模型。改为使用create
。我把你的newToken
方法添加到我的答案中。非常感谢。成功了。顺便说一句,请解释一下为什么“create”在“insert”不可用的情况下使用model?insert被转换成纯SQL insert语句,而create正在以一种雄辩的方式进行。
public function boot(DispatcherContract $events)
{
parent::boot($events);
// Register Event Listeners
\App\Product::updating(function ($product) {
$product->onUpdating();
});
...