Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass request instance to Model Observer, Laravel 5.4

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.

like image 597
Nathan Scherneck Avatar asked May 01 '17 17:05

Nathan Scherneck


2 Answers

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;
}
like image 152
Nathan Scherneck Avatar answered Nov 06 '22 20:11

Nathan Scherneck


You can request object using app helper function of Laravel.

protected $request;

public function __construct(WorkOrderNumber $workorder)
{
    $this->request = app('request');
}
like image 2
Bhushan Avatar answered Nov 06 '22 21:11

Bhushan