Home > Net >  How to avoid duplication in scope Laravel?
How to avoid duplication in scope Laravel?

Time:11-05

I have this scope in the Product model:

public function scopeFirst($query) {
   $query->select('id','name','price','qty');
} 

This scope that I need in a page!

I got another page that needs the same fields but with one or two more columns in select like

public function scopeSecond($query) {
   $query->select('id','name','price','qty','exprie_date');
} 

How to avoid this duplication of these scopes!

Is there any way or I have to have a second one and that it!

CodePudding user response:

This is untested, but you should be able to reuse the first scope and add selected columns to it:

public function scopeSecond($query) {
    $query->first()->addSelect([
        'expire_date',
        'other_column',
        '...',
    ]);
}

The addSelect function allow you to add those columns to the SELECT statement without overriding it completely. This allows you to use the first scope and add additional columns to it as you wanted.

CodePudding user response:

To implement a scope you do not have to select specific fields. Here is an example code from a project:

  // Article search by category with the author relation attached
  public function scopeByCategory(Builder $query, $categoryId): Builder
  {
    $query->with('Author')
      ->where('category_id', $categoryId);
    return $query;
  }

So we see scopes as "Give me the records which match this criteria". We simply query the whole row every time. This also helps with caching to just receive the rows.

So omitting the select will just give you all columns and the full record.

Your scope has no other filters in your example. So is this all you need the scopes for? Limiting results to specific columns?
If you must, go with the other answer(s). Otherwise I want to add this kind of micro-optimization was not worth our time even in larger projects.

In your example you add 'exprie_date' to the selected columns. Why not always all of them? Your implementation did not seem to be cautios because of security. If you want to implement security policies per column, we found that making use of get{Attribute}Attribute works better, for example returning '' if someone does not have access to that column.

  • Related