paranoid
paranoid

Reputation: 7105

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.

Result that I want:

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

Upvotes: 1

Views: 668

Answers (1)

tompec
tompec

Reputation: 1230

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

Upvotes: 3

Related Questions