Pass request instance to Model Observer, Laravel 5.4

eloquent, laravel, php

Solution

This is so simple I'm a bit embarrassed I posted it. Anyway, in case someone finds this thread, here's the solution. In your observer, add a constructor that accepts the request and sets a property.

protected $request;

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

Problem

I've just learned of model observers and would like to move some of my logic from controller to observer. Here's what I have: 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(); } } ``` Problem is accessing the request from within the observer. I don't see anything in the docs. I found one thread here that refers to this and it suggested using the request helper function. I tried `request('site_id')` but it was empty.

Original source