[英]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.