I'm trying to create a query that display all the driver's information and only get the "Year" in created_at column. Can anyone help me? thanks in advance
Here's the response query
"user_id": 45,
"driver_fname": "Sample",
"driver_mname": "Sample",
"driver_lname": "Sample",
"driver_birthday": "2000-07-28",
"years_driving_experience": null,
"years_driving_experience_quicktrans": null,
"start_year_of_exp_in_driving": null,
"start_year_of_exp_in_driving_in_quicktrans": null,
"educational_attainment": null,
"health_status": null,
"drug_test": null,
"marital_status": null,
"Salary_range": null,
"license_registration": null,
"license_expiration": null,
"license_condition": null,
"medication_maintenance": null,
"training": null,
"driver_height": null,
"driver_weight": null,
"weight_status": null,
"emergency_contact_number": null,
"home_address_street_number": null,
"home_address_street": null,
"home_address_brgy": null,
"home_address_city": null,
"work_hours_range": null,
"work_shift": null,
"sleep_hours_range": null,
"smoker": null,
"created_at": "2021-11-23 03:50:33"
the created_at column should be in Year, for example created_at:"2021"
Here is my query code
$driversInformation = DriverInformation::all(['user_id','driver_fname','driver_mname','driver_lname',
'driver_birthday','years_driving_experience','years_driving_experience_quicktrans','start_year_of_exp_in_driving',
'start_year_of_exp_in_driving_in_quicktrans','educational_attainment','health_status','drug_test','marital_status',
'salary_level As Salary_range','license_registration','license_expiration','license_condition','medication_maintenance',
'training','driver_height','driver_weight','weight_status','emergency_contact_number','home_address_street_number',
'home_address_street','home_address_brgy','home_address_city','work_hours_range','work_shift','sleep_hours_range','smoker',
'created_at As year']);
CodePudding user response:
The easiest way is to mutate the date in your DriverInformation
model
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'created_at' => 'datetime:Y',
];
You can read more about mutators here https://laravel.com/docs/8.x/eloquent-mutators#date-casting
CodePudding user response:
SQL Query should be
select Year(createdAt) as Year from Persons;
you can check the example here https://www.db-fiddle.com/f/d5j8icfiw8nvwZdKqhtr4h/0
CodePudding user response:
You can use Carbon class -> \Carbon\Carbon::parse($item->created_at)->format('Y')