How to use Carbon in Laravel query?
Hi,
I wanna get month with Carbon in laravel query, but I am getting error message: "Property [Carbon] does not exist on the Eloquent builder instance."
Here's what I have tried so far-
$data = Profilpenper::join('nilaipers', 'nilaipers.profilpenpers_id', 'profilpenpers.id')
->where('profilpenpers.updated_at', 'like', $year.'%')
->Carbon::parse('profilpenpers.updated_at')->format('m')
->get();
This means a lot to me
@aidil Carbon you need to use https://www.w3schools.com/sql/func_mysql_month.asp
$data = Profilpenper::join('nilaipers', 'nilaipers.profilpenpers_id', 'profilpenpers.id')
->where('profilpenpers.updated_at', 'like', $year.'%')
->select(
'profilpenpers',
'nilaipers',
DB::raw('month(profilpenpers.updated_at) as month')
)
->get();
or you can use Carbon AFTER getting the result for transformation (created_at and updated_at columns casted as Carbon instance automatically)
foreach ($data as $row) {
dd($row->updated_at->format('m'));
}
also check https://laravel.com/docs/9.x/queries#additional-where-clauses whereYear
->whereYear('profilpenpers.updated_at', $year)
@SilenceBringer Sorry, actually I got message: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'profilpenpers' in 'field list'
@silencebringer, thank for clause whereYear .
Btw, in this case I just wanna get 2 digit of month.
@aidil I provided the solution for you
DB::raw('month(profilpenpers.updated_at) as month')
@SilenceBringer I don't see any difference in my browser whether below code is added or not:
->select(
'profilpenpers',
'nilaipers',
DB::raw('month(profilpenpers.updated_at) as month')
)
still shows "Y/m/d H:i:s" format
@aidil
->select(
'profilpenpers.*',
'nilaipers'.*,
DB::raw('month(profilpenpers.updated_at) as month')
)
and in blade you need to show ->month, not ->updated_at. Or (as I told you before) `->updated_at->format('m')
Please or to participate in this conversation.