Want to change date of birth format to dd/mm/yyy in laravel .
Actually i want it to be saved in dd/mm/yyyy format but it should be send to the database in yyyy/mm/dd format . How can it be done ?? . Here is the code
<div class="col-md-4">
<div class="form-group">
<label>Date of Birth:</label>
<span class="data_fields data_personal">{{ date_to_indian($cust_data->dob) }}</span>
<span class="edit_fields edit_personal"><input type="text" class="form-control" value="{{ $cust_data->dob }}" name="dob"></span>
</div>
</div>
Use Carbon's format() method:
Carbon::parse($date)->format('d/m/Y');
If date is in Eloquent $dates property, just use format():
$date->format('d/m/Y')
You can use laravel accessor mutators in laravel. Put below code in your model
protected $dates = [
'dob',
];
//This method automatically save date Y-m-d format in database
public function setDobAttribute($date)
{
$this->attributes['dob'] = Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');
}
//This method automatically fetch date d-m-Y format from database
public function getDobAttribute($date)
{
return Carbon::createFromFormat('Y-m-d', $date)->format('d-m-Y');
}
You must be use carbon class namespace as following:
use Carbon;
Try this code:
<span class="edit_fields edit_personal"><input type="text" class="form-control" value="<?php echo date("d/m/Y",strtotime($cust_data->dob )); ?>" name="dob"></span>
You can use Date Mutators to convert a date to instances of Carbon, which extends the PHP DateTime class to provide an assortment of helpful methods.
Add the following property in your model:
protected $dates = [
'dob',
];
Then use it in your view as:
{{ $cust_data->dob->format('d/m/Y') }}
When retrieving attributes that are listed in your $dates property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon's methods on your attributes
Use carbon date format method format()
{{ Carbon\Carbon::parse($cust_data->dob)->format('d-m-Y') }}
OR
you can use PHP date function date() for it:
{{date('d-m-Y', strtotime($cust_data->dob))}}
Both are return same result but I recommend you to use Carbon because Carbon is inherited from PHP DateTime class.
I think you can try twig filters here {{ $cust_data->dob | date('d-m-Y') }}
<div class="col-md-4">
<div class="form-group">
<label>Date of Birth:</label>
<span class="data_fields data_personal">{{ $cust_data->dob | date('d-m-Y') }}</span>
<span class="edit_fields edit_personal"><input type="text" class="form-control" value="{{ $cust_data->dob }}" name="dob"></span>
</div>
</div>
You can use $cust_data->dob->format('d/m/Y');
for more options http://carbon.nesbot.com/docs/
Related
I'm trying to implement multiple timezone in laravel. I have already JS which collect users Timezone and successfully stored in 'timezone' column in Users table.
I have a view blade where user can choose the date and the time to schedule when their campaign will be sent. Im struggling to pass the users timezone to be shown in the view ("h:i A",). At the moment shows the timezone from config/app.php which is in my case 'Europe/Amsterdam'.
Here is the part of the view with bootstrap datepicker and time.
<div class="form-group">
<div class="col-md-5">
<label for="" class="form-label">Start Sending:</label>
<br>
<input type="radio" name="send_at" #if(old('send_at') != "now") checked #endif value="now" id="send-now">
<label for="send-now">Now</label><br>
<input type="radio" #if($mailing && strtotime($mailing->send_at) > time()) checked #endif name="send_at" value="latter" id="send-latter">
<label for="send-latter">Later</label><br>
<?php
$ts = time();
if($mailing && !old('send_date')) {
$ts = strtotime($mailing->send_at);
} elseif(old('send_date')) {
$ts = strtotime(old('send_date') .' '. old('send_time'));
}
?>
<div class="row">
<div class="col-md-6 pb-20">
<input class="datepicker form-control" type="text" name="send_date" value="{{ date("m/d/Y", $ts) }}">
</div>
<div class="col-md-6">
<div class="input-group bootstrap-timepicker timepicker">
<input type="text" name="send_time" value="{{ date("h:i A", $ts) }}" id="timepicker" class="form-control input-small">
<span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
<span class="input-group-addon">CET</span>
</div>
</div>
</div>
</div>
</div>
I tried to add this kind of attribute in my model but Im not sure which arguments I should add here to get time shown correctly in the view:
public function getCreatedAtAttribute($value)
{
$timezone = optional(auth()->user())->timezone ?? config('app.timezone');
return Carbon::parse($value)->timezone($timezone);
}
Here is the method from the model. I also need to convert time in the Send_At column If user use Australian time for example it will write exact Australian time in the database but campaign will be send 8 hours latter since time different and because my database is setup to European time. Im not sure how to achieve to convert time in that column.
protected $table = 'mailings';
public function saveMailing(User $user, $data)
{
$subscribers = isset($data['subscribers']) && $data['subscribers'] ? $data['subscribers'] : null;
$subscribersIds = array();
if($subscribers) {
$subscribersArr = explode(",", $subscribers);
if(count($subscribersArr) > 0) {
foreach ($subscribersArr as $sid) {
if($sid > 0) {
$subscribersIds[$sid] = $sid;
}
}
}
}
$this->user_id = $user->id;
$this->promo_id = $data['promo_id'];
$this->mailinglist_id = $data['mailinglist_id'] > 0 ? $data['mailinglist_id'] : null;
$this->subject = $data['subject'];
$this->body = $data['body'];
$this->send_at = $data['send_at'];
$this->type = isset($data['type']) && $data['type'] == 'reminder' ? 'reminder' : 'notification';
$this->subscribers = count($subscribersIds) > 0 ? implode(",", $subscribersIds) : null;
$this->save();
}
Thanks for your help!
I believe the easiest solution would be to add the following to the boot method in AppServiceProvider.php
public function boot()
{
date_default_timezone_set('Africa/Lagos');
}
If that doesn't work, you can try replacing time() with laravel's helper method - now(UTC) and provide the timezone as a parameter.
Also, change strtotime as in the following:
Carbon::createFromFormat('Y-m-d H:i:s', $mailing->send_at, 'UTC')
->setTimezone('Africa/Lagos')
you can change datetime format by following
Carbon doc
return Carbon::parse($value)->format('g:i A')->timezone($timezone);
In a Laravel 8 application I have two components. Input.php and Form.php
Input.php
<?php
namespace App\Http\Livewire\General;
use Livewire\Component;
class Input extends Component
{
public $name;
public $model;
public $label;
public function render()
{
return view('livewire.general.input');
}
}
input.blade.php
<div class="mt-3">
<label
for="{{ $name }}"
class="sr-only"
>
$label
</label>
<input
wire:model="{{ $model }}"
id="{{ $name }}"
placeholder="{{ $label }}"
autocomplete="off"
class="w-100 text-lg leading-6 text-gray-500 border border-grey-500 px-4 py-2 rounded"
/>
#error($name)
<p class="text-red-500 mt-1">{{ $message }}</p>
#enderror
</div>
Form.php
<?php
namespace App\Http\Livewire\Event;
use Livewire\Component;
class Form extends Component
{
public $eventName;
public function render()
{
return view('events.livewire.form');
}
}
form.blade.php
<form wire:submit.prevent="submit" method="POST">
#csrf
<livewire:general.input
:name="'event-name'"
:label="'Event Name'"
:model="'eventName'"
/>
</form>
As you can see I am trying to use a property passed from the form.php $eventName into the input component <livewire:general.input :model="'eventName'" /> This then I would expect to be passed to the input.php public property $model which would be tied to the wire:model directive on it's own template.
I'm very new to livewire and haven't used PHP in some time so I may be on the wrong path. I have considered events but am not sure if this is the correct approach.
I am trying to have a child component in livewire be dynamic so it's parents template can define it's reactive properties and pass their values back up for evaluation ect...
I have checked the livewire docs and viewed related but not exactly alike articles on laracasts and various other laravel forums with no result. I have also talked with PHP experts in my office and they say this is technically possible but I may be restricted by how livewire is implementing it's lifecycle events.
Again any information pointing me to documentation or in the right direction is appreciated.
Edit:
I found: Binding Nested Data
on the livewire site https://laravel-livewire.com/docs/2.x/properties
However this does not work in my case... Is there anyone that can show ( using my code an example of this working? )
I have got the desired result my parent component now reacts based on child changes.
This is not automatic in Livewire as per their documentation:
Nesting Components
Livewire supports nesting components. Component nesting can be an extremely powerful technique, but there are a few gotchas worth mentioning up-front:
Nested components CAN accept data parameters from their parents, HOWEVER they are not reactive like props from a Vue component.
j
This means I needed to propagate my own events with they key and value of what I needed the parent to know about.
I did this by adding explicitly setting the key in the template.
#livewire('general.input', ['key' => 'eventName'])
Note: I had to change to the blade style syntax since the tag style does not work with this approach ( I do not know why ).
This then feeds into the Inputs public property $key.
This is used when propagating the event to let the parent which key is being modified.
form.php
<?php
namespace App\Http\Livewire\Event;
use Livewire\Component;
class Form extends Component
{
public $eventName;
public $listeners = ['change' => 'change'];
public function change($data)
{
$this->{$data['key']} = $data['value'];
}
public function render()
{
return view('events.livewire.form');
}
}
form.blade.php
<form wire:submit.prevent="submit" method="POST">
#csrf
{{ $eventName }}
#livewire('general.input', ['key' => 'eventName'])
</form>
input.php
<?php
namespace App\Http\Livewire\General;
use Livewire\Component;
class Input extends Component
{
public $name = 'NAME';
public $model;
public $key;
public $label = 'LABEL';
public $listeners = ['change' => 'change'];
public function change()
{
$this->emitUp('change', [
'key' => $this->key,
'value' => $this->model
]);
}
public function render()
{
return view('livewire.general.input');
}
}
input.blade.php
<div class="mt-3">
<label
for="{{ $name }}"
class="sr-only"
>
{{ $label }}
</label>
<input
wire:keyup="change"
wire:model="model"
id="{{ $name }}"
placeholder="{{ $label }}"
autocomplete="off"
class="w-100 text-lg leading-6 text-gray-500 border border-grey-500 px-4 py-2 rounded"
/>
#error($name)
<p class="text-red-500 mt-1">{{ $message }}</p>
#enderror
</div>
Some values are hard coded for brevity.
how to add date search like DATE_FROM and DATE_TO? i have already existing controller using search box and drop-down filter to my blade template, now how do i add date range filter. and also how to add it inside my date-picker in blade
Note: in my database i only have the default created_at column
Controller:
public function index(Request $request)
{
$search=$request->input('search');
if(request()->has('lead_status')){
$leads=Lead::where('lead_status', request('lead_status'))
->paginate(5)
->appends('lead_status',request('lead_status'));
}
else{
$leads=Lead::orderBy('created_at','desc')->search($search)->paginate(5);
}
return view ('leads.index')->with('leads',$leads);
}
VIEW Date-Picker
<div class="col-sm-4 form-group">
<label>FROM</label>
<input type="date" name="" value="" class="form-control">
</div>
<div class="col-sm-4 form-group">
<label>TO</label>
<input type="date" name="" value="" class="form-control">
</div>
With where date you can search by the date
and may more at here Laravel
Lead::whereDate('created_at', '=', date('Y-m-d'))->get();
WhereBetween
Lead::whereBetween('created_at', [date('Y-m-d', strtotime($input['from'])), date('Y-m-d', strtotime($input['to']))])->get();
Your soluation
$leads = Lead::query();
if($request()->has('lead_status')){
$leads = $leads->where('lead_status', $request('lead_status'));
}
if($request()->has('from') && $request()->has('to')){
{
$from_date = date('Y-m-d', strtotime($request()->has('from')));
$to_date = date('Y-m-d', strtotime($request()->has('to')));
$leads = $leads->whereBetween('created_at', [$from_date, $to_date]);
}
$leads = $leads->orderBy('created_at','desc')->paginate(5);
And in your controller access the request input parameter like so:
use Illuminate\Http\Request;
public function index(Request $request)
{
$search= $request->input('date');
$leads=Lead::where('lead_status''=', $search)->get();
return view ('leads.index')->with('leads',$leads);
}
ROUTE with
Route::get('/leads/{date}', 'YourControllerName#index');
I am getting errors on submitting a form to the server that has a bootstrap-datepicker field. What should I do now?
The error report is:
InvalidArgumentException in Carbon.php line 425:
Unexpected data found.
Unexpected data found.
Data missing
in database migration file:
$table->timestamp('dob'); // dob is date of birth
in my model:
protected $dates = ['dob'];
HTML:
<div class="form-group {{ $errors->has('dob') ? 'has-error' : '' }}">
<label class="col-sm-2 control-label">Birthday*</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="dob" required="" id="datepicker" value="{{ old("dob") }}">
{!! $errors->first('dob','<span class="help-block">:message</span>') !!}
</div>
</div>
script:
<script src="{{ url('js/bootstrap-datepicker.js') }}" charset="utf-8"></script>
<script>
$('#datepicker').datepicker({
autoclose: true
});
</script>
If you're trying to get the bootstrap-datepicker jQuery plugin to work with Laravel date formats, here are the steps:
Step 1, set this format in your JavaScript:
jQuery('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
Step 2, add the time part of the date when saving the date in your Controller, example:
$model->start_date = $request->start_date .' 00:00:00';
The datpicker format is different from timestamp format so you need to follow one of the solutions:
1.change the accepted datepicker's format using format option
2.follow the following link to know how to change the timestamp's format to whatever you want or even make it nullable.
Laravel "Unexpected data found" error when trying to change format of Carbon created_at date
You need to change your field before saving in DD,
In order to do that add something like this function to your relevant model,
Notice that you must follow the naming convention which is //setNameAttribute
. Then pass the date taken from datepicker
public function setDob($date)
{
$this->attributes['dob']=Carbon::createFromFormat('Y-m-d H:i:s',$date);
}
I write the form.blade.php like this:
<div class="form-group">
<label>Start at</label>
<div id="start_date" class="input-group date form_datetime col-md-4" data-date-format="yyyy-mm-dd hh:ii:ss">
<input class="form-control" name="start_at" size="16" type="text" value="{{ $activity->start_at }}">
<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
</div>
</div>
Both Create and Edit method use the view to display the form. In the Edit method, the $activity is used and everything is normal. But in the Create method, the $activity is null, so I have a error in {{ $activity->start_at }}.
I know I can use if(!empty($activity)) to prevent this error. but I do not want to use this anywhere.
What is the better way?
You could use this,
{{ $activity->start_at or '' }}
I also like to reuse code and use the same view to create or edit an object. What I do is to pass a brand new instance of the object to the create view. This way I have the object on its initial state including defaults (if any) and I am able to prefill those defaults (if any) on the displayed form. It gives me an additional benefit: if anything goes wrong with the validation at the server level the user doesn't lose any data, I just need to do something like this in the view:
<div class="form-group">
<label for="test_field" class="control-label">Fecha de firma</label>
<input type="text" value="{{ ( !empty($isabi) ? $isabi->fecha_firma : old('fecha_firma')) }}"
name="fecha_firma" id="isabi-fechafirma" class="form-control" placeholder="Este campo es obligatorio">
</div>
This is the create method with extra functionality removed for clarity (check if the user is authenticated, linking the created object with the company the user works for and other stuff):
public function create()
{
return view('isabis.create', [
"isabi" => new Isabi()
])->with($this->data);
}
I use $this->data for view configuration. Hope this helps.