我刚刚了解了模型观察者,并希望将我的一些逻辑从 Controller 转移到观察者。这是我所拥有的:

应用服务提供者.php

public function boot()
{
    WorkOrder::observe(WorkOrderObserver::class);
}

WorkOrderObserver.php
namespace App\Observers;

use App\Site;
use App\WorkOrder;
use Carbon\Carbon;
use App\WorkOrderNumber;

class WorkOrderObserver
{

    public function creating(WorkOrder $workOrder)
    {
        $branchOfficeId = Site::findOrFail($request->site_id)->branch_office_id;
        $today = Carbon::today('America/Los_Angeles');
        $todaysWorkOrderCount = WorkOrder::where('created_at_pst', '>=', $today)->count();

        $workOrder->work_order_number = (new WorkOrderNumber)
            ->createWorkOrderNumber($branchOfficeId, $todaysWorkOrderCount);
        $workOrder->completed_by = null;
        $workOrder->status_id = 1;
        $workOrder->work_order_billing_status_id = 1;
        $workOrder->created_at_pst = Carbon::now()->timezone('America/Los_Angeles')
            ->toDateTimeString();
    }

}

问题是从观察者内部访问请求。我在文档中没有看到任何内容。我在这里找到了一个线程,它引用了这个,它建议使用请求辅助函数。我试过 request('site_id') 但它是空的。

最佳答案

这太简单了,我有点尴尬我把它贴出来了。无论如何,如果有人找到这个线程,这里是解决方案。在您的观察者中,添加一个接受请求并设置属性的构造函数。

protected $request;

public function __construct(Request $request)
{
    $this->request = $request;
}

关于php - 将请求实例传递给模型观察者,Laravel 5.4,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43723085/

10-13 05:48