将请求实例传递给Model Observer,Laravel 5.4

时间:2017-05-01 17:01:28

标签: php laravel eloquent

我刚刚学会了模型观察者,并希望将我的一些逻辑从控制器转移到观察者。这就是我所拥有的:

AppServiceProvider.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'),但它是空的。

2 个答案:

答案 0 :(得分:6)

这很简单我发布它有点尴尬。无论如何,如果有人找到这个帖子,这就是解决方案。在您的观察者中,添加一个接受请求并设置属性的构造函数。

 int i =cmd.ExecuteNonQuery();
 if(i>0)
 {
     this.BindGrid();
 }

答案 1 :(得分:0)

您可以使用Laravel的应用帮助功能请求对象。

protected $request;

public function __construct(WorkOrderNumber $workorder)
{
    $this->request = app('request');
}