user2727841
user2727841

Reputation: 725

order by not working with mysql date function laravel

I'm working on a query where I've to show the records on ascending order base and in database my table field created_at has 2016-11-29 12:18:22 and I want to retrieve date only so I made laravel query and my laravel query is

$countOffer = countOffer::select(DB::raw("DATE(created_at) AS created_at"))->where("offerStatus", "!=", 7)->orderBy("created_at", "ASC")->get()->toArray();

now the problem is when I add order by clause at created_at field it shows 0000-00-00 so I made query on MySQL yog for testing purpose and query is

SELECT DATE(created_at) AS created_at FROM countOffer WHERE offerStatus != 7 ORDER BY created_at ASC

it is also showing the same value 0000-00-00 and search it on different forums but didn't get any solution related to my problem.

Any help will be appreciated. Thanks in advance

Upvotes: 1

Views: 1249

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

You can get created_at only field by using get(['created_at']):

$countOffers = countOffer:where('offerStatus', '!=', 7)->oldest()->get(['created_at']);

In this case, you're using Eloquent without raw queries and it's so much better to use it to keep your app maintainable.

Also, since created_at is a Carbon instance, you can do this in a controller, view or any other place of your app:

@foreach ($countOffers as $countOffer)
    {{ countOffer->created_at->toDateString() }}
@endforeach

If you need the data for exporting, use the map() collection method to convert Carbon instance to whatever format you want.

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You should update your query like below step

Step 1 :

$countOffer = countOffer::select(DB::raw("DATE(created_at) AS created_at"))
->where("offerStatus", "!=", 7)->orderBy("created_at", "ASC")->get();

Step 2 :

Then you should get the $countOffer array of what you need.

Hope this helps you

Upvotes: 1

Related Questions