在Laravel 5.1中将模型保存到数据库之前执行一些操作 [英] Do something before saving model to database in Laravel 5.1

查看:569
本文介绍了在Laravel 5.1中将模型保存到数据库之前执行一些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 5.1模型中将数据写入数据库之前,我该如何做一些修改,例如修改某些数据字段或进行更多验证? 关于该问题的文档很难在实际应用中使用: http://laravel.com/docs/5.1/eloquent#events

How can I do something such as modify some data fields or more validate before writing data to database in Laravel 5.1 model ? It's document about that problem is hard to use in real application: http://laravel.com/docs/5.1/eloquent#events

我的代码是

<?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';
        });
    }
}

在这种情况下,我总是会出错:

In this case, I always got error:

SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))

我该如何解决?

推荐答案

class Lunch extends Eloquent
{
    protected static function boot()
    {
        static::creating(function ($model) {
            $model->topping = 'Butter';

            return $model->validate();
        });
    }

    protected function validate()
    {
        // Obviously do real validation here :)
        return rand(0, 1) ? true : false;
    }

    public static function newToken($userId, $role)
    {
        static::where('user_id', $userId)->delete();

        return static::create([
            'user_id' => $userId,
            'role' => $role,
        ])->token;
    }
}

这篇关于在Laravel 5.1中将模型保存到数据库之前执行一些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆