Ad

Laravel Cannot Use $this Inside Anonymous Function

- 1 answer

I am using a construct to get request variables only once, since I need to use them in more than one method, I do not want to repeat code.

public function __construct(Request $request)
{
    $this->labelId   = $request->label;
    $this->statusId  = $request->status;
    $this->monthId   = $request->month;
}

This works for my "standard" view, but not for the "label view":

public function standard()
{
    $appointments = Appointment::latest('start')->status($this->statusId)->label($this->labelId)->month($this->monthId)->get();

    return view('appointments.index', compact('appointments'));
}

public function label(Request $request)
{
    $appointments = Label::with(['appointments' => function ($query) use ($this->labelId, $this->statusId, $this->monthId) {
        $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
    }])->get();

    return view('appointments.label', compact('appointments'));
}

I am getting the error:

Cannot use $this as lexical variable

And the issue is here:

function ($query) use ($this->labelId, $this->statusId, $this->monthId)

My question is this, can I somehow use the variables anyway in the label method using the construct, or is there maybe a better way to accomplish this?

Ad

Answer

Replace:

$appointments = Label::with(['appointments' => function ($query) use ($this->labelId, $this->statusId, $this->monthId) {
    $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
}])->get();

With:

$appointments = Label::with(['appointments' => function ($query) {
    $query->label($this->labelId)->status($this->statusId)->month($this->monthId)->get();
}])->get();

You can't pass properties of the current object via use(), and you can't use($this), however, $this is always available in PHP 5.4+.

For this to work properly, you'll need PHP 5.4+. PHP 5.3 and below had a limitation where the local object context cannot be accessed from inside an anonymous function.

It is not possible to use $this from anonymous function before PHP 5.4.0

You could do something like:

$instance = $this;
$appointments = Label::with(['appointments' => function ($query) use ($instance) { // ... }

But then you couldn't access private or protected members; it would be seen as a public access. You really need PHP 5.4 :)

Ad
source: stackoverflow.com
Ad