Laravel Eloquent Pluck produced incorrect data

Viewed 325

Trying to get created_at date using pluck.

        $campaigns_dates = CampaignHistory::where('status', "Complete")->orderBy( 'created_at', 'ASC' )->pluck('created_at');
        $campaigns_dates = json_decode( $campaigns_dates );
        return $campaigns_dates;

//Getting This

["2020-06-29T14:19:03.000000Z","2020-06-29T14:19:42.000000Z","2020-07-29T14:23:54.000000Z","2020-08-28T14:55:53.000000Z","2020-08-29T14:17:40.000000Z","2020-09-29T14:18:27.000000Z","2020-09-29T14:21:13.000000Z"]

//But Want This

Example: ["2020-06-29 14:19:03","2020-06-29 14:19:42"]
3 Answers

You can use the map operation to reformat your date as your given format :

public function index() {
 
    $campaigns_dates = CampaignHistory::orderBy('created_at', 'ASC')
        ->pluck('created_at')
        ->map
        ->format('Y-m-d H:i:s');

    $campaigns_dates = json_decode($campaigns_dates);
    return $campaigns_dates;
}

Alternative Solution : There is an alternative solution with selectRaw() method, thanks to @OMR for provide this solution :

public function index() {
 
    $campaigns_dates = CampaignHistory::orderBy('created_at', 'ASC')
        ->selectRaw("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as formatted_date")
        ->pluck('formatted_date');

    $campaigns_dates = json_decode($campaigns_dates);
    return $campaigns_dates;
}

you can also use an accessor for that ..For that in your model, you have to just put this

public function getCreatedAtAttribute($value)
{
     return Carbon::parse($value)->format('Y-m-d H:i:s') //or what format you need
}
Related