我有一个像这样雄辩的模型:
<?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()
,只使用雄辩的功能。
我想要的结果:
[
{
"title":"NEWS 1",
"desc":"News Description1"
},
{
"title":"NEWS 2",
"desc":"News Description2"
}
]
答案 0 :(得分:3)
在Model类中使用访问器:
public function getTitleAttribute($value)
{
return strtoupper($value);
}
https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor