December 15, 2020
Laravel middleware を実践してみる
laravel middleware で access 履歴
Model Middleware 登録
// Model 作成
php artisan make:model Models/Admin/AccessReport -m
// Middleware 作成
php artisan make:middleware AccessReportMiddleware
Models/Admin/AccessReport.php
namespace App\Models\Admin;
use Illuminate\Database\Eloquent\Model;
class AccessReport extends Model
{
const CREATED_AT = 'access_datetime';
const UPDATED_AT = null;
protected $table = 'access_report';
protected $primaryKey = 'admin_id';
protected $fillable = [
'staff_id', 'execution_file', 'from_ipaddress', 'project_id'
];
protected $hidden = [
];
}
laravel/app/Http/Middleware/AccessReportMiddleware.php
namespace App\Http\Middleware;
use Closure;
use App\Models\Admin\AccessReport;
use \Route;
class AccessReportMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
$this->accessReport($request, $response->status());
return $response;
}
public function accessReport($request, $status)
{
$user = $request -> user();
$data = [
'staff_id' => 1,
'execution_file' => $request -> path(),
'from_ipaddress' => $request -> ip(),
'project_id' => 0,
];
AccessReport::create($data);
}
}
App/Http/Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'acr' => \App\Http\Middleware\AccessReportMiddleware::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
database/migrations/[DATETIME]_create_access_reports_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAccessReportsTable extends Migration
{
public function up()
{
Schema::create('access_report', function (Blueprint $table) {
$table->bigIncrements('report_id');
$table->bigInteger('staff_id');
$table->text('execution_file');
$table->char('from_ipaddress', 15);
$table->dateTime('access_datetime');
$table->bigInteger('project_id');
});
}
public function down()
{
Schema::dropIfExists('access_report');
}
}