meetStackOverflow
meetStackOverflow

Reputation: 11

How to add datetime formate for public function as key(stdClass) in controller/laravel

so I'm trying to get data for my chart from the database and I want it to display a number of orders per day scenario well I tried this code and it gives me full unformatted dates from the database. Any ideas on how to change it to date/month??

    $data = DB::table('analytics')->get();
    $attrs = array();




    foreach ($data as $key => $value) {

        
        // -> as it return std object
        $attrs[$value->created_at][] = $value->order;
    }

    


    // dd($attrs);

    return view('analytic::dashboard.test', compact('attrs'));

Upvotes: 0

Views: 157

Answers (3)

NecklessPork
NecklessPork

Reputation: 53

My recommendation would be to use Eloquent instead of the DB query builder. If you have an Analytic model, then this is quite simple. You could just add created_at to your $dates array and it will automatically be cast as a Carbon instance. For instance, in your model:

protected $dates = ['created_at'];

Upvotes: 0

John Lobo
John Lobo

Reputation: 15319

If you are using collection then

 $user=DB::table('analytics')->get()
                            ->mapToDictionary(function ($analytics){
                                $date=Carbon::parse($analytics->created_at)->format('d-m-Y');
                                $data[$date]=$analytics->order;
                                return $data;
                             })->toArray();

Upvotes: 0

aynber
aynber

Reputation: 23011

$value->created_at is a full date/time string. Since you want to organize it by dates, then you'll need to format it first. Thankfully, Laravel's timestamps are automatically converted to Carbon, so it's easy to format

$attrs[$value->created_at->toDateString()][] = $value->order;

If you want just the year/month, then use format() instead

$attrs[$value->created_at->format('Y-m')][] = $value->order;

Edit I see now you're using query builder (DB), not Eloquent, so you'll need to actually parse the timestamp separately.

$date = Carbon::create($value->created_at);
$attrs[$date->toDateString()][] = $value->order; // 2021-07-14
$attrs[$date->format('Y-m')][] = $value->order;  // 2021-07

Upvotes: 1

Related Questions