N.Tec
N.Tec

Reputation: 127

Laravel Eloquent Pluck produced incorrect data

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"]

Upvotes: 2

Views: 588

Answers (3)

STA
STA

Reputation: 34688

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;
}

Upvotes: 5

Tanvir Ahmed
Tanvir Ahmed

Reputation: 1019

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
}

Upvotes: 0

V-K
V-K

Reputation: 1347

You've got the same date structure as you store in DB. To change id use casts inside CampaignHistory model: https://laravel.com/docs/8.x/eloquent-mutators#date-casting

protected $casts = [
    'created_at' => 'datetime:Y-m-d H:i:s',
];

or you can use function format in the loop.

Upvotes: 0

Related Questions