skip to Main Content

I want to apply some conditions on my models (after retrieving from the database), I found this approach but it has a problem that is for before getting relations and the model has no relations but I want them.

    public static function booted()
    {
        static::retrieved(function (Product $product) // $product has no relations even if use 'with' method.
        {
            // Something that I want to do on my all products to check something on them. (not on a specific field, on entire product) 
            $product->check = new ProductCheck($product);
        });
    }

I always want to map on my collection (or when I get just one product with first method) automatically.

Manually, I have to do this each time I get a product or a collection of products:

$products = Product::with('attributes')->get();

$products = $products->map(function ($product) {
     $product->check = new ProductCheck($product);
     return $product;
});

// Or

$product = Product::with('attributes')->find(1);
$product->check = new ProductCheck($product);

But I want to do this inside the Product model that don’t need to repeat it each time I get products and the closest approach I found was the static::retrieved that does not solve my problem.

Is ther any methods inside models classes that I can map my data after retrieving with relations from the database and before I get them with get or first or any methods like these?

2

Answers


  1. you can use retrieved event like this :

    static::retrieved(function (Product $product) 
        {
            $product->setAttribute('check',new ProductCheck($product));
        });
    
    Login or Signup to reply.
  2. How about using scope in model??

    Add following code in Product model

    public function scopeCheck($query) { 
        // Write your restriction here 
        return $query->where('active', 1); 
    } 
    

    In controller:

    $products = Product::check()->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search