John Davidson

php - Convert database string to date in sql & laravel

0 comments
Message:


I have made a problem here. I have stored date into the database in a string format but now I am finding records on the basis of dates. and it is not working. What is the solution to this problem


datatype : varchar |
data : eg. 01-10-2002


$current_month_balance =
tbl_wallet_detail::
whereMonth('start_date', date('m'))
->whereYear('start_date', date('Y'))
->get();



My Answer:
To convert the database string to a date in SQL, you can use the STR_TO_DATE function. In Laravel, you can use the DB::raw method to execute raw SQL queries. Here is an example of how you can convert the database string to a date in Laravel:

$current_month_balance = tbl_wallet_detail::
whereRaw("STR_TO_DATE(start_date, '%d-%m-%Y') BETWEEN CURDATE() - INTERVAL 1 MONTH AND CURDATE()")
->get();

This query will convert the 'start_date' column from varchar to date format using the STR_TO_DATE function and then compare it with the current month to fetch the records.

Rate this post

3 of 5 based on 3138 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us