How to Select Year and Month from the Created_At Attributes of Database Table in Laravel 5.1

How to select year and month from the created_at attributes of database table in laravel 5.1?

There are date helpers available in the query builder:

$post = Mjblog::whereYear('created_at', '=', $year)
->whereMonth('created_at', '=', $month)
->get();

laravel query builder how to only retrieve year and month from dateTime field

Since you always want that format you can define an Accessor in the HistoryCostEstimation model like this :

public function getCreatedAtAttribute($date) { 
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m');
}

And you can query the records without any transformations :

App\Models\HistoryCostEstimation::where('user_id',$id)
->orde‌​rBy('created_at','de‌​sc')
->get();

How to change default format at created_at and updated_at value laravel

In your Post model add two accessor methods like this:

public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

Now every time you use these properties from your model to show a date these will be presented differently, just the date without the time, for example:

$post = Post::find(1);
echo $post->created_at; // only Y-m-d formatted date will be displayed

So you don't need to change the original type in the database. to change the type in your database you need to change it to Date from Timestamp and you need to do it from your migration (If your using at all) or directly into your database if you are not using migration. The timestamps() method adds these fields (using Migration) and to change these fields during the migration you need to remove the timestamps() method and use date() instead, for example:

$table->date('created_at');
$table->date('updated_at');

How to only use created_at in Laravel

Eloquent does not provide such functionality out of the box, but you can create it on your own using the creating event callback:

class User extends Eloquent {

public $timestamps = false;

public static function boot()
{
parent::boot();

static::creating(function ($model) {
$model->created_at = $model->freshTimestamp();
});
}

}

Laravel Eloquent, group by month/year

You can try as:

->select(DB::raw('count(id) as `data`'), DB::raw("DATE_FORMAT(created_at, '%m-%Y') new_date"),  DB::raw('YEAR(created_at) year, MONTH(created_at) month'))
->groupby('year','month')
->get();


Related Topics



Leave a reply



Submit