dpno17028
dpno17028
2017-07-23 12:06
浏览 71
已采纳

暂时禁用Laravel附加

Is it possible to temporarily disable the appends functionality in Laravel 5.4 during testing?

protected $appends = [
        'full_name',
    ];

I want to ignore that ^.

I've made a model factory but when I'm testing I don't want to have these append items on my model.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doulu7921
    doulu7921 2017-07-23 15:56
    已采纳

    I have had experience with this too. I've found a good solution here.

    But, if you like a one-liner solution, you can also use the ff methods of Eloquent's Model class:

    • setHidden(array $hidden)

    • makeHidden(array|string $attributes)

    You can check these here.

    点赞 评论
  • doujiunai2169
    doujiunai2169 2017-07-23 16:03

    I was thinking something like this:

    /**
     * Get all appended items.
     *
     * @return array
     */
    public function getAppends()
    {
        $vars = get_class_vars(__CLASS__);
    
        return $vars['appends'];
    }
    
    /**
     * Unset all appended items.
     *
     * @return $this
     */
    public function unsetAppends()
    {
        collect($this->getAttributes())->pull($this->getAppends());
    
        return $this;
    }
    

    But @elegisandi thanks that works great.

    点赞 评论
  • douniao7308
    douniao7308 2019-04-29 14:20

    I was using this code is suitable: testing for Model name Product for example

    // get product with "id = 1" for example
    $needed_product = Product::find(1)->toArray();
    
    // remove un-used attributes
    $product = new Product;
    foreach ($product->appends as $attr) {
        unset($needed_product[$attr]);
    }
    

    Now the $needed_product gets without any appends attributes

    点赞 评论

相关推荐