Caner Caner -4 years ago 118
PHP Question

How to use in laravel 5.4 local scope in a relation call?

I use in my project laravel 5.4 and have 2 models, first model is Group and second model ist Ticket.

In model Group I have following relation:

public function tickets() {
return $this->hasMany('App\Models\Ticket', 'group_id');
}


In table tickets (model Ticket) I have a bool field called "open", and the local scope:

public function scopeOpen($query) {
return $query->where('open', 1);
}


How can I filter now by using this relation like:
$group->tickets->open
, do I have

Answer Source

You can define a relation as such:

public function ticketsOpen()
{
   return $this->tickets()->open();
}

and then use it as follows:

$group->ticketsOpen;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download