drn5375 2017-09-17 06:07
浏览 25
已采纳

装饰雄辩的模型属性 - 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.

Result that I want:

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

展开全部

  • 写回答

1条回答 默认 最新

  • dongleibeng5602 2017-09-17 06:23
    关注

    Use an accessor in your Model class:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部