Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

How to resolve ERROR: Trailing data in Laravel Carbon Date

In my Laravel-5.8, I have this model:

use Carbon\Carbon;
class HrHolidayDate extends Model
{
    protected $table = 'hr_holiday_dates';
    protected $fillable = [
                  'holiday_date',
              ];

    protected $dates = [
        'holiday_date'
    ];
            
    public function setHolidayDateAttribute($input)
    {
        $this->attributes['holiday_date'] = Carbon::createFromFormat('d-m-Y', $input);
    } 
    
    public function getHolidayDateAttribute($input)
    { 
        return Carbon::createFromFormat('Y-m-d', $input)->format(config('app.date_format'));   
    }
}

config:

    'date_format' => 'd/m/Y',
    'date_format_js' => 'dd/mm/yy', 

I tried to pass it as JSON from the controller to the view:

public function findNationalHoliday(Request $request)
{
   $nationalholidays               = HrHolidayDate::select('holiday_date')where('company_id', $userCompany)->whereYear('created_at', '=', date('Y'))->get();
 return response()->json([
    'nationalholidays' => $nationalholidays,
 ]);        

}

When I tried to retrieve it from the view:

 <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#leave_type', function() {
            var air_id =  $(this).val();
            var a = $(this).parent();
            var op = "";
            
            $.ajax({
                type: 'get',
                url: '{{ route('get.nationalholidays.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json
                success: function(data) {
                    $('#nationalholidays').val(data.nationalholidays);
                },
                error:function(){

                }
            });
        });
    });
    </script>

I got this error:

[2020-10-06 11:21:46] production.ERROR: Trailing data {"userId":469,"exception":"[object] (InvalidArgumentException(code: 0): Trailing data at C:\xampp\htdocs\myapp\vendor esbot\carbon\src\Carbon\Traits\Creator.php:623) [stacktrace] #0 C:\xampp\htdocs\myapp\vendor esbot\carbon\src\Carbon\Traits\Creator.php(645): Carbon\Carbon::rawCreateFromFormat('Y-m-d', '2020-08-24 00:0...', NULL) #1 C:\xampp\htdocs\myapp\app\Models\Hr\HrHolidayDate.php(110): Carbon\Carbon::createFromFormat('Y-m-d', '2020-08-24 00:0...')

I am using MYSQL DB.

But the datatype is date and not datetype. Why is it adding time in the error shown:

How do I correct this error?

Thank you.

0 likes
8 replies
a4ashraf's avatar

@noblemfd

can you share this function output?


public function findNationalHoliday(Request $request)
{
   $nationalholidays               = HrHolidayDate::select('holiday_date')where('company_id', $userCompany)->whereYear('created_at', '=', date('Y'))->get();
 return response()->json([
    'nationalholidays' => $nationalholidays,
 ]);
bobbybouwmann's avatar

That is because you mix accessors with casts. You should either use a cast or an accessor.

In your case, you can remove the $dates cast here, because you already handle it in your accessor and mutator

2 likes
noblemfd's avatar

@a4ashraf - This is it:

 <script type="text/javascript">
   $(document).ready(function() {
       $(document).on('change', '#leave_type', function() {
         var air_id =  $(this).val();
         var a = $(this).parent();
         var op = "";
        
         $.ajax({
            type: 'get',
            url: '{{ route('get.nationalholidays.all') }}',
            data: { 'id': air_id },
            dataType: 'json',      //return data will be json
            success: function(data) {
                $('#nationalholidays').val(data.nationalholidays);
            },
            error:function(){

            }
        });
     });
    });
    </script>

GET http://localhost:8888/myapp/get/findNationalHoliday?id=2 500 (Internal Server Error) send @ jquery.min.js:2 ajax @ jquery.min.js:2 (anonymous) @ create:681 dispatch @ jquery.min.js:2 v.handle @ jquery.min.js:2 trigger @ jquery.min.js:2 (anonymous) @ jquery.min.js:2 each @ jquery.min.js:2 each @ jquery.min.js:2 trigger @ jquery.min.js:2 n.select @ select2.full.min.js:2 (anonymous) @ select2.full.min.js:2 e.invoke @ select2.full.min.js:2 e.trigger @ select2.full.min.js:2 d.trigger @ select2.full.min.js:2 (anonymous) @ select2.full.min.js:2 e.invoke @ select2.full.min.js:2 e.trigger @ select2.full.min.js:2 (anonymous) @ select2.full.min.js:2 dispatch @ jquery.min.js:2 v.handle @ jquery.min.js:2

Snapey's avatar
Snapey
Best Answer
Level 122

because your database contains hours,minutes and seconds

and you try to parse it to carbon object in format Y-m-d but there is trailing data

Carbon\Carbon::createFromFormat('Y-m-d', '2020-08-24 00:0...')

as the date is in your dates array, Eloquent will convert it to Carbon for you, so just remove the accessor getHolidayDateAttribute

3 likes
noblemfd's avatar

@snapey - I observed that when I changed: get() in

$nationalholidays               = HrHolidayDate::select('holiday_date')where('company_id', $userCompany)->whereYear('created_at', '=', date('Y'))->get();	

to first()

$nationalholidays               = HrHolidayDate::select('holiday_date')where('company_id', $userCompany)->whereYear('created_at', '=', date('Y'))->first();

No error but #leave_type ajax only return one date 24/08/2020. But I need all the holiday dates so that I can use it in the jquery to remove all the holiday dates from start_date and end_date in

    <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#leave_type', function() {
            var air_id =  $(this).val();
            var a = $(this).parent();
            var op = "";
            
            $.ajax({
                type: 'get',
                url: '{{ route('get.employeeleavecounts.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json
                success: function(data) {
                    $('#weekendinclusive').val(data.weekendinclusive);
                },
                error:function(){

                }
            });
        });
    });
    </script>

<script type="text/javascript">
     $(document).ready(function () {
            $("#leave_days").on('keyup blur', function (e) {
            var periodval=parseInt($("#leave_days").val());
            var startDate = $('.commencement_date');
            var endDate = $('.resumption_date');

            var dte = startDate.datepicker("getDate"); 
                    dte.setDate(dte.getDate()+periodval); 
                    endDate.datepicker("setDate", dte);               

          });
            $( '.commencement_date' ).datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,      
                showAnim: 'slideDown',
                duration: 'fast',   
                minDate: +1,
                setDate: new Date(),
                yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
        }).datepicker('setDate', '1');
            $( '.resumption_date' ).datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,      
                showAnim: 'slideDown',
                duration: 'fast',   
                minDate: +1,
                yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
                enableOnReadonly: true,
                beforeShow: function(i) { if ($(i).attr('readonly')) { return false; } }
            });
    });
</script>

so that I can remove the holidays that are in the selected dates

a4ashraf's avatar

@noblemfd

try with this

	//in your model 

	public function getHolidayDateAttribute($value)
    	{ 
        	return Carbon::createFromFormat('Y-m-d', $value);  
    	}

	// in your controller

	public function findNationalHoliday(Request $request)
	{
		$nationalholidays = HrHolidayDate::select('holiday_date')
			->where('company_id', $userCompany)
			->whereYear('created_at', date('Y'))->get();

		return response()->json([
			'nationalholidays' => $nationalholidays
		]);
	}
noblemfd's avatar

@snapey - When I removed the accessor getHolidayDateAttribute

the error is nor more there it displays the date as this:

(6) [{…}, {…}, {…}, {…}, {…}, {…}]
0: {holiday_date: "2020-08-24 00:00:00"}
1: {holiday_date: "2020-08-26 00:00:00"}
2: {holiday_date: "2020-09-25 00:00:00"}
3: {holiday_date: "2020-11-30 00:00:00"}
4: {holiday_date: "2020-09-25 00:00:00"}
5: {holiday_date: "2020-09-30 00:00:00"}
length: 6
__proto__: Array(0)

But this makes it to throw another error when I wanted to display the holiday_date in the blade using:

{{ Carbon\Carbon::createFromFormat('d/m/Y', $holiday->holiday_date)->format('d-m-Y') }}

I have:

production.ERROR: The separation symbol could not be found

But it is stored as date in the DB and not datetime.

What do I do?

Snapey's avatar

in blade you can use the Carbon object as it is. You don't need to parse it again.

{{ $holiday->holiday_date)->format('d-m-Y') }}

Please or to participate in this conversation.