Laravel date error in query builder after parsing the date too - laravel

I am using query builder to fetch some data but for the created_at date I am using Carbon::parse(), but it's giving me error something like this:
DateTime::__construct(): Failed to parse time string
Can someone tell me what's wrong with this?
My query:
Carbon::parse(DB::table('students_attendances')
->join('students_classes', 'students_attendances.class_id', '=', 'students_classes.id')
->select('students_attendances.id', 'students_classes.class_name', 'students_attendances.created_at')
->orderBy('id', 'asc')->get())->toCookieString();

Related

Laravel 8: why is sorting by date in eloquent is wrong, using Carbon

Possible duplicates:
Laravel: How to order date, change the date format and group by the date?
Laravel Carbon format wrong date
I created a line chart using chartjs, the chart and data fetching is working fine. However the order of the dates is wrong. It starts off with Aug 2022 instead of Jan 2022.
When I use the orderBy(), it shows orderBy() doesn't exists error.
When I use createFromFormat() of Carbon, it shows missing data error.
Why? I parsed the date with Carbon and the column type is datetime, shouldn't it be working?
This is my laravel collection:
$data = TrafficViolation::select('id', 'violationDateTime')
->get()
->sortBy('violationDateTime')
->groupBy(function($data) {
return Carbon::parse($data['violationDateTime'])->format('M, Y');
});
The orderBy() is a Query Builder method. Once you call get(), you get a Collection instance.
To order the records in your DB you need to call orderBy() first, and than get():
UPDATE:
I have included the records count, and date format. You still need to order the records by the violationDateTime column
$data = User::selectRaw('COUNT(*) as violation_count, DATE_FORMAT(violationDateTime, \'%M, %Y\') as formatedDate')
->groupBy('formatedDate')
->orderBy('violationDateTime')
->get();
if your get a Syntax error or access violation: 1055 you need to change the stritc mode in mysql to false in /config/database.php change ['connections' => ['mysql' => ['strict' => false]]]

Laravel Query builder - ->offset() doesnt want to work with computed column

I'm using query builder and have this query which works
$athletes = DB::table('athletes')
->select("athletes.first_name", "athletes.last_name",
DB::raw('MAX(performance) AS personal_best')
)
->leftJoin("performances", "athletes.id", "=", "performances.athlete_id")
->groupBy("athletes.id", "athletes.first_name", "athletes.last_name")
->orderBy("personal_best", "DESC")
->get();
but now I need to do pagination so I added
->offset(5)
->limit(10)
and now it is giving me an error:
Invalid column name 'personal_best'
I was trying to find a solution to this but so far with no success. If anybody has any idea it would be very welcomed!

Query using eloquent whereMonth where date is string

In one of the tables a column with type of varchar contains a date with the following format day-month-year. I would like to run a query using eloquent on that table with whereYear and whereMonth, but I get an error since the column booking_date is not of type Date.
The query I am trying to run is
MyTable::whereYear('booking_date', '=', $year)
->whereMonth('booking_date', '=', $month)
->get();
And getting the following error
"SQLSTATE[42883]: Undefined function: 7 ERROR: function pg_catalog.date_part(unknown, character varying) does not exist\nLINE 1: ...\" = $1 and \"said_table\".\"deleted_at\" is null) and extract(ye...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts.
Is there a way to cast the string value to a date before querying it, maybe with using raw expressions? If yes, any hints would be great.
If this field is going to be a date on the particular model all the time (and with a name like 'booking_date', it might well be), it is even easier than having to deal with it on every query. You can cast it within the dates field on the model itself:
protected $dates = [
'booking_date',
];
By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, and the above will do the same for booking_date. No further casting required. From Laravel docs on date mutators
You may easily achieve that thanks to Carbon library which is included within Laravel:
use Carbon\Carbon;
$targetDate = Carbon::now()->year($year)->month($month);
MyTable::whereYear('booking_date', '=', $targetDate)
->whereMonth('booking_date', '=', $targetDate)
->get();

Laravel Datepicker Failed to parse time string

I'm trying to build a query in Laravel using whereBetween and I have a problem with the dates-range. I'm using Carbon to get the inputs, looking like this:
$dateRange = Carbon::parse($request->get('anniversary'));
I received the following error on submit:
DateTime::__construct(): Failed to parse time string (06/01/2019 - 06/30/2019) at position 11 (-): Unexpected character
Then, I changed the $dateRange in this form:
$dateRange = Carbon::parse(str_replace('-', '', $request->get('anniversary')));
After that, this error occured:
DateTime::__construct(): Failed to parse time string (06/01/2019 06/30/2019) at position 12 (0): Double date specification
The whereBetween clause looks like this:
->whereBetween('anniversary', [$dateRange])
Any ideas on how can I fix this?
You need to explode the retrieved Datepicker to two values. (Start Date and End Date)
$dateArray = explode('-', $request->get('anniversary'));
$startDate = $dateArray[0];
$endDate = $dateArray[1];
Now you can use
->whereBetween('anniversary', $dateArray);

Select Query - Upto Previous Date Records is Not Working in Laravel

Following Laravel Query I Write for to get Upto Previous Date Records that's not getting any Records. If I Remove Date query its get Many Records.
$data['frmdate_submit'] format is 2017-05-24.
How to Fix this Problem
$getpreviousbalance = Companyledger::where('transaction_date', '>', $data['frmdate_submit'])
->WhereIn('frm_ledger', $ledgerlist)
->where('company_id', $companyids)
->get();
Use whereData instead of where when you are checking with dates.
$getpreviousbalance=Companyledger::whereDate('transaction_date','>',$data['frmdate_submit'])->WhereIn('frm_ledger',$ledgerlist)->where('company_id',$companyids)->get();
hope this will works.
$getpreviousbalance = Companyledger::where('company_id', $companyids)
->whereIn('frm_ledger', $ledgerlist)
->where('transaction_date', '>', \Carbon\Carbon::parse($data['frmdate_submit']))
->get();

Resources