Laravel date time condition not working properly - laravel

I have two columns in my offer table as follow, I want to fetch those offer's record which is currently active:
offer_start_date
offer_end_date
24-10-2022 10:57:00
24-10-2023 10:57:00
Below is my query date condition working fine but time is giving problems:
$now = Carbon::now();
$today = $now->toDateString();
$currentTime = $now->toTimeString();
$offers_data = Offer::whereRaw("offer_status=2 and offer_type=1 and is_special_offer=3")
->whereDate('offer_start_date','<=',$today)
->whereTime('offer_start_date','<=',$currentTime)
->whereDate('offer_end_date','>=',$today)
->whereTime('offer_end_date','>=',$currentTime)
->limit(10)
->get();
What would be the reason?

Using whereDate and whereTime together is likely not working the way you think it is.
Instead, try just using where() and Laravel will work it out for you.
$now = Carbon::now();
$offers_data = Offer::whereRaw("offer_status=2 and offer_type=1 and is_special_offer=3")
->where('offer_start_date', '<=', $now)
->where('offer_end_date', '>=', $now)
->limit(10)
->get();

Related

access data from database to compare with current date to calculate total days

I have tried to access date stored in my db table and compare it with current date so that I can get the number of days but it shows this error
DateTime::__construct(): Failed to parse time string ([{"quit_date":null},{"quit_date":null}]) at position 0 ([): Unexpected character
This is the code that use in my controller
$quit_date = Information::select('quit_date')
->where('user_id','=',\Auth::user()->id)
->get();
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);
but if I set the $quit_date manually with the date for example "2019-04-25 00:00:00.000000", the code works fine and shows the days different between the dates, but when I use the Information::select to read the date from database, it shows error.
use Auth; //top of controller
$checkdate = Information::
->where('user_id','=',Auth::user()->id)
->first();
$quit_date=$checkdate->quit_date;
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);
The issue occurs because you are using ->get() at the end of your query. That method returns a Collection not a single object. The issue is solved by using ->first() to return a single object.
The error itself is because in the line $date = new Carbon($quit_date);, Carbon cannot convert a Collection to a date.
This should work:
$quit_date = Information::select('quit_date')
->where('user_id','=', \Auth::user()->id)
->first(); //Changed this from ->get()
$date = new Carbon($quit_date);
$now = Carbon::now();
$day = $date->diffInDays($now);

Using day, Month or Year as MYSQL query filter in Laravel

In my code, i am querying a database by accepting month and year input from user.
I have tried writing it the normal PHP way and other ways i can find online but none seems to be working. here is the code i am using currently
$salesmonth = $request->input('mn');
$salesyear = $request->input('yr');
$id = Auth::user()->id;
$comm = \DB::table('bakerysales')
->where([
['customer_id', '=', $id], [MONTH('sales_date'), '=', $salesmonth], [YEAR('sales_date
'), '=', $salesyear]
])
->get();
return view::make('showCommission')->with('comm', $comm);
I expect the query to return data from rows that match user selected month and year
Laravel comes with a few different where clauses for dealing with dates e.g.
whereDate / whereMonth / whereDay / whereYear.
This means that your controller method can look something like:
$comm = \DB::table('bakerysales')
->where('customer_id', auth()->id())
->whereMonth('sales_date', $request->input('mn'))
->whereYear('sales_date', $request->input('yr'))
->get();
return view('showCommission', compact('comm'));

Counting columns with if conidition in query

Counting only columns in which, Buy_Rate is more than Sell_Rate.
My query is not resulting as per expected, it is resulting me wrong.
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->where('buy_rate', '<', 'sell_rate')->get()->count();
Inverse: If sell_rate is more than buy_rate then only, count the columns.
You can use whereColumn
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)
->whereColumn('buy_rate', '<', 'sell_rate')
->count();
Also there is no need to call get() when you need count() from query builder
laravel eloquent where don't support comparing columns. so you need use raw SQL in order to compair two columns. you can do something like,
$user_id = Auth::user()->id;
$losing_trades_count = FinalTrade::where('user_id', '=', $user_id)->whereRaw('buy_rate < sell_rate')->get()->count();
hope this helps!

Select with advanced where clauses and timestamp using Carbon and DB

I have a code to generate a SQL query from a table.
I want to select items that exist between dates and a true value in another field.
DB use in construction and Carbon facades, following advice on how to work with Carbon in laravel 5.
But I do not get the effect I returns all rows
private function runBids() {
$dt = Carbon::parse(Config::get('constants.start_lot'));
$start = $dt->toDateTimeString(); // 2006-05-08 08:34:59
$end = $dt->addDay()->startOfDay(); // 2006-05-09 00:00:00
$lots = DB::table('lots')
->select('id')
->where('end',false)
->where('end_auction', '<=', $end)
->where('end_auction', '=>', $start) // Not work. Return 0 results
// if comment ->where('end_auction', '=>', $start) result 39 results with date
// between dates
// (start it's date of first element of table order by end_auction)
->get();
$lots_id = array();
foreach ($lots as $value){
$lots_id[] = $value->id;
}
dd($lots_id);
}
It all seems correct, except for the operator used on the $start parameter. You have
->where('end_auction', '=>', $start)
And you should have
->where('end_auction', '>=', $start)
Notice the difference between => and >=. The first throws a MySQL error. You could try to wrap that code around a try ... catch block, and check the exception message.
You can also log the executed queries using one of this answers, to check the executed query whenever you don't get the expected results.

HOW TO: Laravel 5 - mySQL query

the situation:
I have one mySQL database and I want to get a dinstinct count of the column C_ID where the set timestamp is like the current day (e.g. 2015-08-14)
in phpMyAdmin it works fine:
SELECT COUNT(DISTINCT C_ID) FROM table WHERE touched_at LIKE '2015-08-14%'
the result is 32; but in Laravel 5 I get 320 because the distinct function does not work for me
$date = date('Y-m-d');
$one = DB::table('talbe')
->select()
->where('touched_at', 'like', "$date%")
->distinct('C_ID')
->count();
Can you please assist me with this problem?
Thanks in advance
Timo
This may work. Tried it in one of my projects and that produces the right answer for me.
$one = DB::table('talbe')
->where('touched_at', 'like', "$date%")
->count(DB::raw('distinct C_ID'));
Try this if it works:
$date = date('Y-m-d');
$one = DB::table('talbe')
->select('touched_at')
->where('touched_at', 'like', "$date%")
->distinct('C_ID')
->count();
You may also try this code
$date = date('Y-m-d');
$one = DB::table('table')
->select(DB::raw('count(Distinct C_ID) as C_ID'))
->where('touched_at', 'like', "$date%")
->get();

Resources