Laravel 5.3 Reach Back

advertisements

I'm having problem with this scope in my product Model

My scope look like this:

public function scopeLessNinetyDays( $query ){

    $date = new \Carbon\Carbon;
    $date->subWeek(12); 

    return $query->where('created_at', '<', $date->toDateTimeString())->get() ;
}

I tried to loop it in category and the result is at the bottom. I need to return true or false. If the product created_at is in 12 weeks already. This is weird because it returns collection. Instead of single product.

 @foreach( $category->product->take(4) as $product )
       {{ dd($product->lessNinetyDays()) }}
    @endforeach

If I used this code it returns single product. See Image at the bottom.

@foreach( $category->product->take(4) as $product )
   {{ dd($product) }}
@endforeach

I don't know how to achieved that goal because of the results.


You are wrongly using a Local Scope. Scopes are used when selecting rows from the database, only that match the defined scope.

What you are looking for, is something like a "fake attribute" (accessor), which is probably the most Eloquent way of achieving what you are wishing for.

First, define this accessor:

public function getIsLessNinetyDaysAttribute() {
  $date = (new \Carbon\Carbon)->subWeek(12);

  return $this->created_at->lt($date);
}

Now, you can access this property by using:

@foreach( $category->product->take(4) as $product )
   {{ dd($product->is_less_ninety_days) }}
@endforeach

This should return either true or false.


Example for using a local Scope

After defining this scope:

public function scopeLessNinetyDays( $query ){

  $date = new \Carbon\Carbon;
  $date->subWeek(12); 

  return $query->where('created_at', '<', $date->toDateTimeString())->get();
}

Now, you can chain this scope to your select query:

@foreach( $category->product->lessNinetyDays()->get() as $product )
   {{ dd($product) }}
@endforeach

In this foreach loop, the only rows returned are the rows that are matching the lessNinetyDays scope.

There a multiple ways to achieve your goal, but in such cases, I always prefer an accessor.