php - Query Scope for this eloquent method?

one text

Solution:

You can define local scopes on the model to refactor the query. Here are few:

class Ticket extends Model
{
use SoftDeletes;

public function scopeByAuthUser($query)
{
    return $query->where('user_id','=', \Auth::user()->id);
}

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

public function scopePending($query)
{
    return $query->where('status_id', 2);
}

public function scopeClose($query)
{
    return $query->where('status_id', 2);
}


 
}

Here's how you can refactor your condition:

 // for the first query
 $tickets = Ticket::with('users','ticketStatus','ticketType','tbl_contacts')
                ->byAuthUser()
                ->latest();

 if(request('Open') || request('Pending') || request('Close')) {
   $scope = strtolower(request('Open') ?? request('Pending') ?? request('Close'));
   $tickets = $tickets->{$scope}()->get();
 } else {
  $tickets = $tickets->get();
 }

Source