简体   繁体   中英

Laravel schema builder, update nullable timestamp field

I am developing a project where I have to store information of a job. For example job_start_date,job_end_date,payment_received_date . It will be nullable initially. As soon as the job starts admin will update job_start_date and job_end_date column. So I cannot set current date and time as default to those field. The problem is, while updating the job_start_date field, if laravel finds that the job_start_date column is null, it throws an error. Call to a member function format() on a non-object. Even though I have declared protected $dates = ['job_start_date','job_end_date','payment_received_date']; in my model. Any suggestion to overcome this problem?

example code:

<!-- job start date -->
  <div class="form-group {{ $errors->has('job_start_date') ? 'has-error' : '' }}">
    <label class="col-md-4 control-label" for="job_start_date">Job Start Date</label>
    <div class="col-md-4">
    <input id="job_start_date" name="job_start_date" type="date" value="{{ $job_account_detail->job_start_date->format('Y-m-d') }}" class="form-control input-md">
    {!! $errors->first('job_start_date','<span class="help-block">:message</span>') !!}
    </div>
  </div>

You can check for null value in your view to avoid the error

<input id="job_start_date" name="job_start_date" type="date" value="{{ !is_null($job_account_detail->job_start_date) ? $job_account_detail->job_start_date->format('Y-m-d') : "" }}" class="form-control input-md">

I would add a method in the model to handle validation and formatting to make my life easier:

// in your model
public function getJobStartDateInDateStringFormat() {

    return !is_null($this->job_start_date)
           ? $this->job_start_date->format("Y-m-d")
           : "";

}

Then in your view you can just call the method:

<input id="job_start_date" name="job_start_date" type="date" value="{{ $job_account_detail->getJobStartDateInDateStringFormat() }}" class="form-control input-md">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM