Diego Cespedes
Diego Cespedes

Reputation: 1353

Laravel 5.1 - get month and day of date (with different variables)

i have my article resource controller, like this:

public function articles()
{
    $articles = Article::OrderBy('id','DESC')->paginate(3);
    return view('blog', compact('articles'));
}

I would like to pass two variables to my view, like this:

$day = day of created article 
$month = month of created article 
return view('blog', compact('articles','day','month'));

But I don't know how to get this data from the database, I can get the date of creation like this :

$article->created_at

How can I get only the day and the month to pass to my view?

Upvotes: 2

Views: 8876

Answers (2)

Chris Forrence
Chris Forrence

Reputation: 10094

By default, created_at is cast to a Carbon instance (reference). Because of that, you can get the day and month attributes directly from the property!

@foreach($articles as $article)
    {{ $article->created_at->day }}
    {{ $article->created_at->month }}
@endforeach

Upvotes: 5

Drown
Drown

Reputation: 5982

The created_at attribute should be a datetime in Laravel.

To get the day and month from it, you can do this :

$day = date('d', strtotime($article->created_at));
$month = date('m', strtotime($article->created_at));

Upvotes: 1

Related Questions