major697
major697

Reputation: 1862

How to delete duplicate date

I have a project in Laravel. I want returned date with table "transmits" with column "created_at". This column is type datetime.

enter image description here

When I returned date on my site I have this:

Select date: 2016-08-24 2016-08-24 2016-08-24 2016-08-24 2016-08-25 2016-08-25

I want the date to be displayed individually. Like this:

Select date: 2016-08-24 2016-08-25

My code:

print $dayDate = (Carbon::createFromFormat('Y-m-d H:i:s', $days->created_at)->format('Y-m-d'));

I can't using groupBy in query to databse, because created_at column is the date and hour. The hour differ from each other, therefore I can not use a groupBy. I can't also use array_unique(), because variable $dayDate returned this when i using var_dump:

string(10) "2016-08-24" string(10) "2016-08-24" string(10) "2016-08-24" string(10) "2016-08-24" string(10) "2016-08-25" string(10) "2016-08-25"

Each date is a separate table. I do not know how I can combine them into a single table.

Edit: In file view:

@foreach($day as $days)
   <?php 
   $dayDate = (Carbon::createFromFormat('Y-m-d H:i:s', $days->created_at)->format('Y-m-d'));
   var_dump ($dayDate);

   ?>
@endforeach

And in file controller:

$day = transmit::select('created_at')->groupBy('created_at')->get();

My post is not duplicate this post [MySQL Query GROUP BY day / month / year][2]

[2]: MySQL Query GROUP BY day / month / year, because in my column created_at is date, hour, munte and secon, therefore I can not use the groupBy.

Upvotes: 1

Views: 479

Answers (2)

aditya7822
aditya7822

Reputation: 23

If you have dates as string, you can:

<?php
$old_dates = "2016-08-24 2016-08-24 2016-08-24 2016-08-24 2016-08-25 2016-08-25";
$new_dates = implode(" ", array_unique(explode(" ", $old_dates)));
echo $new_dates;

Upvotes: 0

Andrej
Andrej

Reputation: 7504

Use the following expression

$day = transmit::selectRaw('date(created_at) as created_date')->groupBy('created_date')->get();

One drawback is mysql can't use index on the field created_at so it will slow down the query.

Upvotes: 1

Related Questions