Laravel 5 unique (database) validation with different date format - php

I'm using laravel 5.5 with MySQL database.
Here is my current code:
private function setValidationRule(Request $request,$actionCode) {
$rules = [];
$rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';
return $rules;
}
public function postCreate(Request $request) {
//Previous code...
$validator = \Validator::make($request->all(),
$this->setValidationRule($request,$actionCode),
$this->setCustomValidationRuleMsg($request,$actionCode)
);
$validator->setAttributeNames($this->setValidationAttributeNames());
if ($validator->fails()) {
$view = $viewPri->withErrors($validator)->withInput();
} else {
$view = $viewSec;
}
return $view;
}
The posting data from client is DD-MM-YYYY = '15-10-2018'.
Then i want to validate the date uniqueness with the rule :
$rules['odaydate'] = 'required|unique:empofday|date_format:"d-m-Y"';
Yes the validation is true (success) but the laravel generated sql was wrong to get the uniqueness :
select count(*) as aggregate from empofday where odaydate = '15-10-2018'
so the resulting sql would be 0 instead of 1.
But if i try manual sql with the following code :
select count(*) as aggregate from empofday where odaydate = '2018-10-01'
resulting value 1.
So, my question is how to set date format for laravel validating uniqueness on database to use d-m-Y format instead of Y-m-d?
Thanks for the help.

If you are using simple text box for date input, I recommend to change that to some date picker plugin, the plugins do have functionality to have a date format that is displayed different than what is sent back to the database.
After that you can remove the date format validation, because it will be managed by the plugin, and unique will run because the format sent by the plugin can be set to be in MySQL format (YYYY-MM-DD)
For jQuery UI Date picker
http://api.jqueryui.com/datepicker/#option-altFormat

Related

how to get specific date result in laravel?

example i am passing this date in $date = 2020-12-28 15:15:53
and
in db approve_date = 2020-12-28 15:15:00
i am trying to get all the record of date only like this 2020-12-28
so i tried
public function getdatedInvoice($date)
{
$invoices = Invoice::where('user_id' , Auth::id())->where('is_approved' , 1)->whereDate('approve_date' , $date)->get();
dd($invoices);
return view('approved_invoices', compact('invoices'));
}
but when i try to use whereDate it gives me nothing how i can get that data according to date?
First of all, by default, Laravel will only process the approve_date column from your database as a string, even if you set it as a date_time column.
To make Laravel process it as a real date instead, you need to add this to the top of your Invoice model:
class Invoice extends Model {
protected $dates = [
'approve_date'
];
}
Now you will be able to make date comparisons without getting weird errors.
To make your date formatted the way you want, you can go about it in 2 ways.
You can either set a default date formats on every date column in your model by adding this also to the model:
protected $dateFormat = 'Y-m-d';
https://laravel.com/docs/5.2/eloquent-mutators#date-mutators
You can also do this at runtime in your view: {{ \Carbon\Carbon::parse($invoice->approve_date)->format('Y-m-d') }}
'approve_date' is not a variable... you are missing the $ sign. It should be something like this:
$invoices = Invoice::where('user_id' ,
Auth::id())->where('is_approved' , 1)->whereDate('$approve_date' ,
$date)->get();
that variable is not being declared in the function;
After all that, you have your date like date/time and you should convert the format using (for example) Carbon https://carbon.nesbot.com/docs/

How Can I convert Laravel default timestamp of created_at filed in a Controller and return through API

I want to get last record updated time in a proper format. Right now updated_at field is default laravel field. The code below return through API as json data: updated_at: "2020-08-01T09:10:01.000000Z"
This is not readable. I tried different conversion method, No one worked.
Code in controller:
public function index()
{
$updatedon = Corona::all('updated_at')->last();
return $updatedon;
}
There are two ways you can do
in your Corona model you can add
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
you can change the format as you wish, you can read more about Accessor
while getting the last record you can do
collect(Corona::all('updated_at')->last())->map(function ($updated_at) {
return Carbon\Carbon::createFromTimeString($updated_at)->format('Y-m-d');
}))
or simply you can do this
$last_record = Corona::all('updated_at')->last();
return \Carbon\Carbon::createFromTimeString($last_record->updated_at)->format('Y-m-d');
By default, Eloquent converts the timestamps columns to instances of Carbon
$updateon->diffForHumans();
https://carbon.nesbot.com/docs/#api-humandiff
This will give you human readable format like 1 day ago, etc
OR
to any custom format
$updateon->format('Y-m-d');

How to format a date in Laravel using ::lists

I am coding a feature in Laravel where a user can use a select box to choose a certain date. By standard, these dates are saved in y-m-d in my table.
I have succeeded in formatting the date to dd/mm/yyyy by using the Eloquent solution, adding to my Eloquent Model called Dataslot:
protected $dates = ['maand'];
Afterwards I could use the following to format the date.
$d = Dataslot::find(1);
$dformat = $d->maand->format('d-m-Y');
In order to pass the ID of the dataslot and the date to my select box, I have chosen to use the lists method.
$dataslots = Dataslot::lists("maand","id");
This returns me an array. I cannot use the format method on this array as I could on the object in the first example.
How can I have an array of formated dates, with the ID as a key, to send to my view?
Untested (I'm on mobile right now) but this should work;
Carbon::setToStringFormat('d-m-Y');
$dataslots = Dataslot::lists('maand', 'id');
You could change Carbon back after with:
Carbon::resetToStringFormat();
this did the trick:
$dataslots = Dataslot::all();
foreach ($dataslots as $o) {
$flatArray[$o->id] = $o->maand->format('d-m-Y');
}
Would this do it?
$dataslots = Dataslots::all()->map(function($dataslot) {
return [$dataslot->id => $dataslot->maand->format('d-m-Y')];
});

Convert String to Carbon

I am using Laravel 5.1
Few days ago I used protected $dates = ['license_expire'] in my model to convert the string date to Carbon instances. In HTML the default value in create form for the date was Carbon\Carbon::now()->format('Y-m-d')
In order to show alert in home page i used <p>Licence Expired: <b>{{ $employee->license_expire < Carbon\Carbon::now()?'License has expired':$employee->license_expire->diffForHumans() }}</b></p>
Till then diffForHumans() method works fine.
But in that case the edit form's default value also was today's date no matter what was in database(I am using a partial form). To resolve it I change the default value in HTML was NUll. And add another method in my model to show current date in create form.
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date)->format('Y-m-d');
}
After that when i go to home page i have an FatalErrorException which says Call to a member function diffForHumans() on string
When I check the date with dd($employee->license_expire) it become STRING again.
Can anybody tell me how can I convert the string to Carbon in this situation?
or
Make my create form's default date as today's date, the edit form's date from database and I can use diffForHumans() to show alert in home page?
You were almost there.
Remove protected $dates = ['license_expire']
and then change your LicenseExpire accessor to:
public function getLicenseExpireAttribute($date)
{
return Carbon::parse($date);
}
This way it will return a Carbon instance no matter what.
So for your form you would just have $employee->license_expire->format('Y-m-d') (or whatever format is required) and diffForHumans() should work on your home page as well.
If you're using Laravel 9+, you can alternatively use the updated syntax for defining Accessors :
use Illuminate\Database\Eloquent\Casts\Attribute;
public function licenseExpire(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value);
);
}
Why not try using the following:
$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');
$filter['dateOfService']='06.2021';
$d1 = Carbon::createFromFormat('m.Y', $filter['dateOfService'], 'Europe/Warsaw')->format('m.Y');
Try this
$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

How do I format data for each row fetched? (Codeigniter, My_Model)

I have a table called events and I'm storing the start date in the datetime format.
However, I'm using a plugin that the requires the dates are formatted to:
YYYY-MM-DD.
I would, therefore, only like to select part of the datetime but without modifying the underling table structure. Is there a way to format the field data for each record as it is being fetched? The reason I ask is because it seems inefficient to go through each record again (like I am at the moment) and format one field.
$this->load->model('event_model');
$events = $this->event_model->get_all();
foreach ($events as $event) {
$start = date('Y-m-d', strtotime($event->start));
//add event to new event array
}
$output = json_encode($events); // I would like to use the formatted date when using json_encode on $events.
I'm using codeigniter with My Model.
why you dont just stored to your generated model?
for example:
$this->load->model("event_model");
$events = $this->event_model->get_all();
foreach($events as $event){
$event->mydate = date('Y-m-d',strtotime($event->start));
}
now pass your $events to the view and use mydate property.
Simply format your date in your sql code
SELECT *, FORMAT(start,'YYYY-MM-DD') as eventStart
FROM events
Format it in the query itself.

Categories