Select with advanced where clauses and timestamp using Carbon and DB - laravel

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.

Related

How to make aritmetic operations from latest record to the previous one in Laravel

I acomplished this when user make input like this:
$CalcPrevNumb = model::latest()->first();
$student = new model([
'recordtime' => $request->get('recordtime'),
'obem_sprqmo_pr_den' => $request->get('cname2') - $CalcPrevDay->cname2
]);
$student->save();
But now the goal is to do this when for example csv file is imported in to the DB(pgsql). Now I need to substract the last created and the previous one.
Something like this?
$CalcPrevNumb = model::latest()->first(); // not the latest but previous
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, cname2 - $CalcPrevNumb')
->orderBy('recordtime', 'ASC')
->get();
How to do this in Elequent?
You may use the skip and take methods to limit the number of results returned from the query or to skip a given number of results in the query
Official Doc
Working solution:
// create object for the prev day
$user = model::whereBetween('recordtime',$dateScope)->selectRaw('recordtime')->first();
// if no records for current day don't brake the code
if($user === Null){
$user = model::latest('recordtime')->first();
}
$CalcPrevDay = model::where('recordtime', '<', $user->recordtime)
->latest('recordtime')
->first();
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, (cname2 - ?) as obem_sprqmo_pr_den', [$CalcPrevDay->obem_m3])
->orderBy('recordtime', 'ASC')
->get();
I tryed:
$students = model::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime, (cname2 - :CalcPrevDay) as obem_sprqmo_pr_den', array('CalcPrevDay'=>$CalcPrevDay->cname2))
->orderBy('recordtime', 'ASC')
->get();
But error occurred:
SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters
Can't understand why but stick to my first solution. If someone have better solution will wait for it.

I want to find the value who exist in array

I have 2 queries and I would like to know the elements (date_debut) of the second query which exists in the first query (dateincal). The elements of the second query can appear one or more times in the first query.
once the dates (date debut) (dateincal) have been found i want to be able to then retrieve also the other information for the element found
$feries = Jourferie::Select('dateincal', 'description')
->where('dateincal', '>=', Carbon::now()->startOfMonth())
->where('dateincal', '<=', Carbon::now()->endOfMonth())
->get();
$plannings = Planning::Select('date_debut', 'id', 'agent_id', 'site_id')
->where('id', '!=', 0)
->where('statut', 'provisoire')
->get();
I don't know if that way can help you:
foreach($feries as $ferie){
$myresult = $plannings->contains('date_debut',$ferie->dateincal)
/* do things */
}

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'));

Laravel Date comparison not working in Eloquent query

I do not understand why but following query return null resultset.
due_date is Carbon date and $now=Carbon:today();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>=',$now)
->where('due_date','<',$now->addMonth())
->get();
Also when I use whereBetween it doesn't work.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$now, $now->addMonth()])
->get();
But when I just to greater than or lesser than it works
$subQuery = BillTable::where('busi_id', $business->busi_id)
->where('due_date','>',$now->addWeek())
->get();
What am I missing here?
The problem here is that you are using the same instance for both range limits. When you call addMonth you add the month to the instance stored in $now. The two examples below illustrate the issue:
1. Using and modifying the same variable in two separate statements works as you'd expect:
$now = Carbon::now();
dump($now); // prints 2015-12-12 14:50:00.000000
dump($now->addMonth); // prints 2016-01-12 14:50:00.000000
2. Using the same variable and modifying it in the same statement that passes the values to a method, will work differently, because it will be evaluated before being passed to the method. Meaning that both parameters will be equal because they both contain the same instance from the $now variable, which after getting evaluated will contain the DateTime of one month from now.
$now = Carbon::now();
// Calling `addMonth` will change the value stored in `$now`
dump($now, $now->addMonth());
// The above statement prints two identical DateTime values a month from now:
// 2016-01-12 14:50:00.000000 and 2016-01-12 14:50:00.000000
This means that your current code was checking if the entries were due only exactly one month from now.
To fix it you need to use two instances in two separate variables:
$from = Carbon::now();
$to = Carbon::now()->addMonth();
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[$from, $to])
->get();
It looks like it is because I used '$now' in the query.
Like is said before the query I did $now=Carbon::today(); and use $now in the query.
But then I got rid of that and changed the query to use Carbon::today() it worked.
$subQuery = BillTable::where('busi_id', $business->busi_id)
->whereBetween('due_date',[Carbon::today(), Carbon::today()->addMonth())
->get();
It is weird.
Thanks,
K

Resources