Find different between two dates from database and save different to database in Laravel

i have simple Laravel booking system and i want to calc my price of booking.First one i need to find different between my records (time_from) and (time_to),then i think,i need to save this data to database and multiply on my room price per night.How can i do it? If you have a solution easier then please tell me.I am new in Laravel and wait for your help.

Its my BookingsController:

<?php

namespace App\Http\Controllers\Admin;

use App\Booking;
use App\Room;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreBookingsRequest;
use App\Http\Requests\Admin\UpdateBookingsRequest;

class BookingsController extends Controller
{
    /**
     * Display a listing of Booking.
     *
     * @return \Illuminate\Http\Response
     */
    public function index( )
    {
        if (!Gate::allows('booking_access')) {
            return abort(401);
        }


        if (request('show_deleted') == 1) {
            if (!Gate::allows('booking_delete')) {
                return abort(401);
            }
            $bookings = Booking::onlyTrashed()->get();
        } else {
            $bookings = Booking::all();
        }

        return view('admin.bookings.index', compact('bookings'));
    }

    /**
     * Show the form for creating new Booking.
     *
     * @return \Illuminate\Http\Response
     */
    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'),'');
        return view('admin.bookings.create', compact('rooms','users'));
    }

    /**
     * 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);
        }
        $booking = Booking::create($request->all());
        \Session::flash('flash_message','Your reservation was successfully created. Awaiting confirmation from the administrator');
        return redirect()->route('home');
    }


    /**
     * Show the form for editing Booking.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (!Gate::allows('booking_edit')) {
            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'),'');
        $booking = Booking::findOrFail($id);

        return view('admin.bookings.edit', compact('booking', 'rooms','users'));
    }

    /**
     * Update Booking in storage.
     *
     * @param  \App\Http\Requests\UpdateBookingsRequest $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateBookingsRequest $request, $id)
    {
        if (!Gate::allows('booking_edit')) {
            return abort(401);
        }
        $booking = Booking::findOrFail($id);
        $booking->update($request->all());


        return redirect()->route('admin.bookings.index');
    }


    /**
     * Display Booking.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        if (!Gate::allows('booking_view')) {
            return abort(401);
        }
        $booking = Booking::findOrFail($id);

        return view('admin.bookings.show', compact('booking'));
    }


    /**
     * Remove Booking from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (!Gate::allows('booking_delete')) {
            return abort(401);
        }
        $booking = Booking::findOrFail($id);
        $booking->delete();

        return redirect()->route('admin.bookings.index');
    }

    /**
     * Delete all selected Booking at once.
     *
     * @param Request $request
     */
    public function massDestroy(Request $request)
    {
        if (!Gate::allows('booking_delete')) {
            return abort(401);
        }
        if ($request->input('ids')) {
            $entries = Booking::whereIn('id', $request->input('ids'))->get();

            foreach ($entries as $entry) {
                $entry->delete();
            }
        }
    }


    /**
     * Restore Booking from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function restore($id)
    {
        if (!Gate::allows('booking_delete')) {
            return abort(401);
        }
        $booking = Booking::onlyTrashed()->findOrFail($id);
        $booking->restore();

        return redirect()->route('admin.bookings.index');
    }

    /**
     * Permanently delete Booking from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function perma_del($id)
    {
        if (!Gate::allows('booking_delete')) {
            return abort(401);
        }
        $booking = Booking::onlyTrashed()->findOrFail($id);
        $booking->forceDelete();

        return redirect()->route('admin.bookings.index');
    }
}

Booking.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
use Auth;

/**
 * Class Booking
 *
 * @package App
 * @property string $room
 * @property string $time_from
 * @property string $time_to
 * @property text $additional_information
 */
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'];
    /**
     * 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 '';
        }
    }

    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id')->withTrashed();
    }


    public function user()
    {
        return $this ->belongsTo(User::class,'user_id');
    }

    public function getFullNameAttribute()
    {
        return $this->first_name . ' ' . $this->last_name;
    }
}

And my database

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->timestamps();
                $table->softDeletes();

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

Upvotes: 2

Views: 277

Answers (3)

Raju Rayhan
Raju Rayhan

Reputation: 101

To get difference between two dates -

$time_from      = date_create('2019-11-01'); // Replace '2019-11-01' string with your DB/Input Value
$time_to        = date_create('2019-11-06'); // Replace '2019-11-01' string with your DB/Input Value
$diff           = date_diff($time_from,$time_to); 
$diff_days      = $diff->format("%a");

NOTE: This will return 5 which means the difference between '2019-11-01' and '2019-11-06'. But in your case, you might have to add 1 with $diff_days to get the visitor duration.

Upvotes: 0

Khem Raj Regmi
Khem Raj Regmi

Reputation: 2270

you can do like this

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

you need to pass false as 2nd argument to diffInDays method otherwise you will always get positive result.

Upvotes: 1

basha
basha

Reputation: 142

You may want to subtract timestamps, knowing that time_to will always be higher than time_from, we will simply do next:

// Note: $booking is a defined object of Booking model
($booking->time_to->timestamp) - ($booking->time_from->timestamp)

As far as you can see, we'll get an integer as a value of subtraction of these two timestamps. You can divide the result with 86400 which is a number of seconds of one day to get number of days of the booking.

You may want to add a function which will consume mentioned code and return number of days of a booking anytime you want to gather the difference, or you can store it into the database.

Upvotes: 1

Related Questions