i am reading Brent Roose's book Laravel, beyond crud. on page 57, he states this example:
class InvoiceQueryBuilder extends Builder
{
public function wherePaid(): self
{
return $this->whereState('status', Paid::class);
}
}
I am confused however about the :self - what is this returning?
CodePudding user response:
In this context, self
is just a shortcut for whatever the current class is. So this:
class InvoiceQueryBuilder extends Builder
{
public function wherePaid(): self
{
return $this->whereState('status', Paid::class);
}
}
Is the same as this:
class InvoiceQueryBuilder extends Builder
{
public function wherePaid(): InvoiceQueryBuilder
{
return $this->whereState('status', Paid::class);
}
}
CodePudding user response:
self
is specified when you are returning an instance of the current class you're working in - in this case inside that method whereState
- it is probably doing something and then returning $this
.
This is useful for situations where you want to chain methods, ex:
$invoice = new InvoiceBuilder();
$invoice->wherePaid()->whereInvoiceEmailed();