[英]Decorate eloquent model attribute - Laravel 5
I have an eloquent model like this: 我有一个这样雄辩的模型:
<?php
namespace News\Model;
class News extends Model
{
public $fillable = [
'title',
'desc'
];
public function getUpperTitle(){
return strtoupper($this->title);
}
}
and have controller like this: 并有这样的控制器:
use News;
class NewsController extends Controller
{
public function index()
{
return News::all();
}
}
Now I want to return all news with uppercase of title (title Decorated) without call getUpperTitle()
and just use eloquent function. 现在我想以大写的标题(标题装饰)返回所有新闻而不调用getUpperTitle()
并只使用eloquent函数。
Result that I want: 我想要的结果:
[
{
"title":"NEWS 1",
"desc":"News Description1"
},
{
"title":"NEWS 2",
"desc":"News Description2"
}
]
Use an accessor in your Model class: 在Model类中使用访问器:
public function getTitleAttribute($value)
{
return strtoupper($value);
}
https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.