【问题标题】:Decorate eloquent model attribute - Laravel 5装饰雄辩的模型属性 - Laravel 5
【发布时间】:2017-09-19 14:37:55
【问题描述】:

我有这样一个雄辩的模型:

<?php

 namespace News\Model;

 class News extends Model
 {
    public $fillable = [
      'title',
      'desc'
    ];

    public function getUpperTitle(){
         return strtoupper($this->title);      
    }

  }

并拥有这样的控制器:

use News;
class NewsController extends Controller
{

      public function index()
      {
            return News::all();
      }
}

现在我想返回所有标题大写的新闻(标题装饰)而不调用getUpperTitle(),只使用 eloquent 函数。

我想要的结果:

[
  {
    "title":"NEWS 1",
    "desc":"News Description1"
  },
  {
    "title":"NEWS 2",
    "desc":"News Description2"
  }
]

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    在模型类中使用访问器:

    public function getTitleAttribute($value)
    {
        return strtoupper($value);
    }
    

    https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2015-07-09
      • 2016-05-23
      • 2017-11-19
      • 1970-01-01
      • 2015-08-15
      • 1970-01-01
      • 2015-05-22
      • 2019-02-12
      相关资源
      最近更新 更多