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.
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;
}
You can request object using app helper function of Laravel.
protected $request;
public function __construct(WorkOrderNumber $workorder)
{
$this->request = app('request');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With