Skip to content
Advertisement

manipulate a result set from laravel eloquent

I’ve just picked up laravel after deciding to move to a php framework. I’m retrieving a result set of articles from a database using an eloquent query:

$posts = Article::select(array('articles.id','articles.article_date','articles.image_link','articles.headline','articles.category', 'articles.published'));

this works fine and results come out as expected.

However I now want to change the format of the article date from the mysql date format to another for the entire collection.

I thought about iterating through the object and changing using the usual php methods but wondered if there was an easier way to manipulate the data either when initiating the query or en mass with the object itself.

I’ve looked at mutators? but wasnt sure if this was appropriate or how to implement

Any help, pointers appreciated

Advertisement

Answer

You’re right, mutators are the way to go. (Laravel 3 syntax)

Getter and Setter documentation for Eloquent models

public function get_article_date()
{
    return date('d-m-Y H:i:s', strtotime($this->get_attribute('article_date'));
}

Getting the attribute

$articles = Articles::get(array(
    'article_date', 
    'image_link', 
    'headline', 
    'published'
));

foreach($articles as $article)
{
    echo $article->article_date;
}

Every time you get the date from your model it will run through the mutator first returning your modified result.

Absolutely no need to run raw queries for something like this.

EDIT got set and get mixed up… more coffee needed (answer edited)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement