在Laravel中检索数据后如何“格式化”数据?

I often parse or format data after pulling it from the database, for example to "humanize" dates before giving feeding them to the view.

This is the code I have, it works but the format() step has to be done manually after each request, on all the results.

class Article extends Eloquent {

    public static $table = 'articles';

    public function format()
    {
        $this->formatted_date = date("M. j, Y", strtotime($this->date));
        $this->body = auto_paragraph(texturize($this->body));
    }
}

and

class Front_Articles_Controller extends Base_Controller
{
    public function action_index() {
        $vars['articles'] = Article::take(10)->get();

        // this is the loop I want to avoid
        foreach ($vars['articles'] as &$article) {
            $article->format();
        }

        return View::make('front.articles.index', $vars);
    }
}

Is there a way to have this formatting function be called automatically on all the Articles or is this the only solution?

this might help or give you a starting point.

class Article extends Eloquent {

public static $table = 'articles';
// set accessor
public function getDateformat($date)
  {
    return date("M. j, Y", strtotime($this->date));

  }
/ /set mutator
public function setDateformat($date)
  {
   // your code here

  }
}

for dates, following is straightforward

class Article extends Eloquent {

    public static $table = 'articles';

    protected $dates = ['date'];
}

And the $article->date will be converted to a Carbon object which is an extended DateTime object.

For other properties, try to use the accessor:

class Article extends Eloquent {

    public static $table = 'articles';

    public function getBodyAttribute($value)
    {
        return auto_paragraph(texturize($value));
    }
}

And then in your controller, $article->body will have the formatted value.

You should implement the Presenter Pattern. This will decouple the raw data (your models) from how you want it presented.

Following this tutorial you should end up with something like this:

Model:

class Article extends Eloquent {
  public static $table = 'articles';
  // $dates will automatically mutate your date to a Carbon object
  protected $dates = ['date'];
}

Presenter:

Class ArticlePresenter extends Presenter {
  public function formattedDate()
  {
    // format is a method of Carbon object
    return $this->date->format("M. j, Y");
  }
}

Usage(in view):

@foreach($articles as $article) 
  {{ $article->present()->formattedDate }}
@endforeach

N.B: for dates manipulation you should use Carbon