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

vkot91's avatar

Difference between two dates in Laravel

Hello guys,i have two tables , rooms and bookings:

 public function up()
    {
        if(! Schema::hasTable('bookings')) {
            Schema::create('bookings', function (Blueprint $table) {
                $table->increments('id');
                $table->datetime('time_from')->nullable();
                $table->datetime('time_to')->nullable();
                $table->integer('diff_days')->nullable();
                $table->text('additional_information')->nullable();
                $table->string('first_name');
                $table->string('last_name');
                $table->string('address')->nullable();
                $table->string('phone')->nullable();
                $table->string('email');
                $table->integer('all_price')->nullable();
                $table->string('isActive')->default('Inactive');


                $table->timestamps();
                $table->softDeletes();

                $table->index(['deleted_at']);
            });
        }
    }
 public function up()
    {
        if(! Schema::hasTable('rooms')) {
            Schema::create('rooms', function (Blueprint $table) {
                $table->increments('id');
                $table->string('room_number');
                $table->integer('floor')->nullable();
                $table->text('description')->nullable();
                $table->integer('price');
                $table->timestamps();
                $table->softDeletes();

                $table->index(['deleted_at']);
            });
        }
    }

Its my BookingController.php

public function create()
    {
        if (!Gate::allows('booking_create')) {
            return abort(401);
        }


        $rooms = Room::get()->pluck('room_number', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        $users = User::get()->pluck('id','id')->prepend(trans('quickadmin.qa_please_select'),'');
        $rooms2 = Room::get()->pluck('price', 'id');
        return view('admin.bookings.create', compact('rooms','users','rooms2'));
    }

And some code frome my booking creating:

                  <div class="col-xs-12 form-group">
                      {!! Form::label('email', trans('quickadmin.bookings.fields.email').'*', ['class' => 'control-label']) !!}
                      {!! Form::email('email', old('email'), ['class' => 'form-control', 'placeholder' => '', 'required' => '']) !!}
                      <p class="help-block"></p>
                      @if($errors->has('email'))
                          <p class="help-block">
                              {{ $errors->first('email') }}
                          </p>
                      @endif
                  </div>
              </div>
            <div class="row">
                <div class="col-xs-12 form-group">
                    {!! Form::label('room_id', trans('quickadmin.bookings.fields.room').'', ['class' => 'control-label']) !!}
                    {!! Form::select('room_id', $rooms, old('room_id'), ['class' => 'form-control ','placeholder' => '','required' => '']) !!}
                    <p class="help-block"></p>
                    @if($errors->has('room_id'))
                        <p class="help-block">
                            {{ $errors->first('room_id') }}
                        </p>
                    @endif
                </div>
            </div>


            <div class="row">
                <div class="col-xs-12 form-group">
                    {!! Form::label('time_from', trans('quickadmin.bookings.fields.time-from').'*', ['class' => 'control-label']) !!}
                    {!! Form::text('time_from', old('time_from'), ['class' => 'form-control datetimepicker','id'=>'datetimepicker1', 'placeholder' => '', 'required' => '']) !!}
                    <p class="help-block"></p>
                    @if($errors->has('time_from'))
                        <p class="help-block">
                            {{ $errors->first('time_from') }}
                        </p>
                    @endif
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12 form-group">
                    {!! Form::label('time_to', trans('quickadmin.bookings.fields.time-to').'*', ['class' => 'control-label']) !!}
                    {!! Form::text('time_to', old('time_to'), ['class' => 'form-control datetimepicker','id'=>'datetimepicker2', 'placeholder' => '', 'required' => '']) !!}
                    <p class="help-block"></p>
                    @if($errors->has('time_to'))
                        <p class="help-block">
                            {{ $errors->first('time_to') }}
                        </p>
                    @endif
                </div>
            </div>

Create dates with Carbon in my Booking php

public function setTimeFromAttribute($input)
    {
        if ($input != null && $input != '') {
            $this->attributes['time_from'] = Carbon::createFromFormat(config('app.date_format') . ' H:i', $input)->format('Y-m-d H:i');
        } else {
            $this->attributes['time_from'] = null;
        }
    }

    public function getTimeFromAttribute($input)
    {
        $zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format') . ' H:i:s');

        if ($input != $zeroDate && $input != null) {
            return Carbon::createFromFormat('Y-m-d H:i:s', $input)->format(config('app.date_format') . ' H:i:s');
        } else {
            return '';
        }
    }

   
    public function setTimeToAttribute($input)
    {
        if ($input != null && $input != '') {
            $this->attributes['time_to'] = Carbon::createFromFormat(config('app.date_format') . ' H:i', $input)->format('Y-m-d H:i');
        } else {
            $this->attributes['time_to'] = null;
        }
    }

    
    public function getTimeToAttribute($input)
    {
        $zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format') . ' H:i');

        if ($input != $zeroDate && $input != null) {
            return Carbon::createFromFormat('Y-m-d H:i:s', $input)->format(config('app.date_format') . ' H:i:s');
        } else {
            return '';
        }
    }

Now i want to check this two dates and calculate total price by multiplying diffence between this two dates and room price.How i can do it?

0 likes
18 replies
aurawindsurfing's avatar

Hey @vkot91

If they are both instances of Carbonthen you can simply compare them like this:

$difference = $startDate->diffInDays($endDate);

Hope it helps!

1 like
rodrigo.pedra's avatar

As both are Carbon instances you can do this:

if (is_null($booking->time_to) || is_null($booking->time_from)) {
  $diff = 0; // or throw new \InvalidArgumentException();
} else {
  $diff = $booking->time_to->diffInDays($booking->time_from);
}

note that Carbon also has diffInHours, and others.

ChristophHarms's avatar

Just calculate the difference between two dates like described in the documentation:

$roomPricePerDay = 4990; // room price in cents

$toDate = Carbon::createMidnightDate(2019, 11, 20);
$fromDate = Carbon::createMidnightDate(2019, 11, 18);

$diffDays = $fromDate->diffInDays($toDate); // 2

$roomPrice = $diffDays * $roomPricePerDay; // 9980 
ChristophHarms's avatar

Whoops, others were faster. :) Funny, when you ask a question that can easily be answered by looking at one page of documentation, you either get rushed with answers or you get an "RTFM". :D

vkot91's avatar

I need to create new function in Booking.php and check it here or where i need to write this code?

vkot91's avatar

I tried do this in my Controller and its dont work

public function create(Request $request)
    {
        if (!Gate::allows('booking_create')) {
            return abort(401);
        }


        $rooms = Room::get()->pluck('room_number', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        $users = User::get()->pluck('id','id')->prepend(trans('quickadmin.qa_please_select'),'');
        $rooms2 = Room::get()->pluck('price', 'id');


        $start_time = new Carbon($request->input('time_from'));
        $finish_time = new Carbon($request->input('time_to'));
        $diff_days = $start_time->diff($finish_time);
        return view('admin.bookings.create', compact('rooms','users','rooms2',"diff_days"));
    }
rodrigo.pedra's avatar

The method you should call is ->diffInDays($finish_time) not ->diff($finish_time)

vkot91's avatar

I try , but its doesnt work too , any errors , but no changes in database

rodrigo.pedra's avatar

Well after calculating the difference you are not saving it anywhere, just passing to the view.

rodrigo.pedra's avatar

Try adding this before the return statement:

Booking::create([
    'time_from' => $start_time->format('Y-m-d H:i:s'),
    'time_to' => $finish_time->format('Y-m-d H:i:s'),
    'diff_days' => $diff_days,

    // by your code I can't figure out where to find this data
    // but as these columns are not nullable on the bookings table
    // you should fill it
    'first_name' => '',
    'last_name' => '',
    'email' => '',
]);

Make sure your Booking model has the correct $fillable fields, or have protected $guarded = [];

vkot91's avatar

Its my Booking.php

class Booking extends Model
{
    use SoftDeletes;

    protected $fillable = ['time_from', 'time_to', 'diff_days', 'additional_information', 'room_id', 'first_name', 'last_name', 'address', 'phone', 'email', 'user_id', 'all_price', 'isActive'];
    /**
     * Set to null if empty
     * @param $input
     */


    /**
     * Set to null if empty
     * @param $input
     */
    public function setRoomIdAttribute($input)
    {
        $this->attributes['room_id'] = $input ? $input : null;

    }

    public function setUserIdAttribute($input)
    {
        $this->attributes['user_id'] = $input ? $input : null;

    }

    /**
     * Set attribute to date format
     * @param $input
     */
    public function setTimeFromAttribute($input)
    {
        if ($input != null && $input != '') {
            $this->attributes['time_from'] = Carbon::createFromFormat(config('app.date_format') . ' H:i', $input)->format('Y-m-d H:i');
        } else {
            $this->attributes['time_from'] = null;
        }
    }

    /**
     * Get attribute from date format
     * @param $input
     *
     * @return string
     */
    public function getTimeFromAttribute($input)
    {
        $zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format') . ' H:i:s');

        if ($input != $zeroDate && $input != null) {
            return Carbon::createFromFormat('Y-m-d H:i:s', $input)->format(config('app.date_format') . ' H:i:s');
        } else {
            return '';
        }
    }

    /**
     * Set attribute to date format
     * @param $input
     */
    public function setTimeToAttribute($input)
    {
        if ($input != null && $input != '') {
            $this->attributes['time_to'] = Carbon::createFromFormat(config('app.date_format') . ' H:i', $input)->format('Y-m-d H:i');
        } else {
            $this->attributes['time_to'] = null;
        }
    }

    /**
     * Get attribute from date format
     * @param $input
     *
     * @return string
     */
    public function getTimeToAttribute($input)
    {
        $zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format') . ' H:i');

        if ($input != $zeroDate && $input != null) {
            return Carbon::createFromFormat('Y-m-d H:i:s', $input)->format(config('app.date_format') . ' H:i:s');
        } else {
            return '';
        }
    }

My Controller

 public function create(Request $request)
    {
        if (!Gate::allows('booking_create')) {
            return abort(401);
        }


        $rooms = Room::get()->pluck('room_number', 'id')->prepend(trans('quickadmin.qa_please_select'), '');
        $users = User::get()->pluck('id','id')->prepend(trans('quickadmin.qa_please_select'),'');
        $rooms2 = Room::get()->pluck('price', 'id');
        $time_from = $request->input('time_from');
        $time_to = $request->input('time_to');

     
        return view('admin.bookings.create', compact('rooms','users','rooms2'));
    }

    /**
     * Store a newly created Booking in storage.
     *
     * @param  \App\Http\Requests\StoreBookingsRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreBookingsRequest $request)
    {
        if (!Gate::allows('booking_create')) {
            return abort(401);
        }

        $start_time = Carbon::parse($request->input('time_from'));
        $finish_time = Carbon::parse($request->input('time_to'));
        $diff_days = $start_time->diffInDays($finish_time);

        $booking = Booking::create([ 'diff_days' => $diff_days,$request->all()]);
        \Session::flash('flash_message','Your reservation was successfully created. Awaiting confirmation from the administrator');
        return redirect()->route('home');
    }

It show me an error

SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into `bookings` (`diff_days`, `updated_at`, `created_at`) values (0, 2019-11-20 13:28:56, 2019-11-20 13:28:56))

Like it doesn't see my other data from inputs,but when i delete diff_date everything work but without difference between this dates

rodrigo.pedra's avatar
Level 56

Change the creation to this:

// get input as an array
$attributes = $request->all();

// add a new key to the attributes
$attributes['diff_days'] = $diff_days;

$booking = Booking::create($attributes);

This will add a new value to the reuslt of $request->all()

The way you were doing you will end up with an array inside other array which Laravel doesn't know how to parse.

1 like
vkot91's avatar

Its work now,Thank you ,and how i can calculate total price?Where i can multiply price of room on this difference?

rodrigo.pedra's avatar

Are you sending the room id with the request? If so try the following:

$room = Room::findOrFail($request->input('room_id'));

$attributes = $request->all();
$attributes['diff_days'] = $diff_days;
$attributes['all_price'] = $diff_days * $root->price;

$booking = Booking::create($attributes);
1 like
vkot91's avatar

It's work.Thank you very much , you really help me.

1 like

Please or to participate in this conversation.