如何在模型中实现owen-it / laravel-auditing

时间:2017-05-15 02:38:07

标签: php laravel model laravel-5.4 audit

我想在我的模型中创建审计跟踪。我已经通过Composer安装了owen-it / laravel-auditing软件包。我的问题是如何在我的模型或控制器中实现它。请参阅下面的控制器和型号代码。感谢

我的控制器:

<?php

namespace App\Http\Controllers;

use App\Events\Test;
use App\Letter;
use App\Notifications\LetterNotification;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Validator;

class LetterController extends Controller
{
    public function viewLetter()
    {
        return view('welcome');
    }

    /**
     * Saves email into database
     *
     * @param  array  $data
     * @return Letter
     */
    protected function create(array $data)
    {
        $letter = Letter::create([
            'email' => $data['email']
        ]);
        $this->letterNotify($letter);

        return $letter;
    }

    /**
     * Validates email
     */
    public function createLetter(Request $request)
    {
        $this->validate($request,[
            'email' => 'required|email|max:255|unique:letters'
        ],[
            'email.required' => 'Email is required.',
            'email.unique' => 'Already registered.',
            'email.email' => 'Please put a valid Email address'
        ]);

        $this->create($request->all());

        return redirect('/')->with('info','You are now registered.');
    }

    protected function letterNotify($letter)
    {`enter code here`
        Notification::send($letter, new LetterNotification($letter));
    }


}

对于我的模特:

<?php

namespace App;

use OwenIt\Auditing\Auditable;
use OwenIt\Auditing\Contracts\Auditable as AuditableContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Letter extends Model implements AuditableContract
{
    use Notifiable;

    use Auditable;

    protected $fillable = ['email'];

    protected $table = 'letters';
}

1 个答案:

答案 0 :(得分:1)

就像我在评论中所述,Laravel审计包仅触发对涉及Eloquent模型和事件的数据库操作的审计(默认情况下为createdupdateddeletedrestored)。

话虽如此,这里是登录/注销时创建审核的步骤列表:

  • Illuminate\Auth\Events\Login事件创建一个侦听器;
  • 触发后,更新users表中跟踪最新登录日期/时间的列(例如latest_login_at);
  • (可选)使用上一个登录日期/时间更新列(例如last_login_at);
  • 通过对users表执行这些更新,Auditor启动;
  • 您还可以收听OwenIt\Auditing\Events\AuditingOwenIt\Auditing\Events\Audited个事件,并在需要时应用更多逻辑;
  • 按照Illuminate\Auth\Events\Logout事件的相同步骤;