繁体   English   中英

装饰雄辩的模型属性 - Laravel 5

[英]Decorate eloquent model attribute - Laravel 5

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

<?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"
  }
]

在Model类中使用访问器:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM