Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

362
Views
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.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
}
about 4 years ago · Santiago Trujillo Report

0

You can request object using app helper function of Laravel.

protected $request;

public function __construct(WorkOrderNumber $workorder)
{
    $this->request = app('request');
}
about 4 years ago · Santiago Trujillo Report

0

get request data in observer laravel

request() helper should work:

if (request()->has('password')) {
    $user->password = bcrypt(request()->password);
}

ref: https://www.codegrepper.com/code-examples/php/get+request+data+in+observer+laravel

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!