In this article we will be building a time tracking application using Laravel, also one of the most popular PHP frameworks and Vue, one of the most popular JavaScript frameworks.

Toggl is a time tracking application that allows you know how much time is spent on a particular task. With Toggl you can add multiple projects and track how much time you have spent on each of the features in that project. This is useful because it will give a detailed report of how much time a project cost.

The application will look like this when we are done:

Requirements

To follow along in this article, you need the following requirements:

When you have all the requirements, we can proceed.

Setting Up Our Laravel Application

The first thing we would do is set up our Laravel application. In a terminal, run the command below to create a new Laravel application:

    $ laravel new timetracker

When the application is created, cd to the directory and open it in your favorite editor. The first thing we will do is create our migrations, controllers and models. In the terminal, run the command below to create them:

    $ php artisan make:model Project -mc
    $ php artisan make:model Timer -mc

The command above will not only create the Models, it will also create the migrations and controllers due to the -mc flag. This is a great way to quickly create several components that would have otherwise been done one after the other.

Here is a screenshot of what we get after running the commands above:

Creating Our Project Database Migration, Model and Controller

Let us start editing the files we just generated. First, we will start with the Project migration, model and the controller. In the databases/migrations directory, open the *_create_projects_table.php file and paste the following code:

    <?php

    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

    class CreateProjectsTable extends Migration
    {
        public function up()
        {
            Schema::create('projects', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->unsignedInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users');
                $table->timestamps();
            });
        }

        public function down()
        {
            Schema::dropIfExists('projects');
        }
    }

The migration above is a representation of the database schema.

Next, open the Project model file, ./app/Project.php, and paste the code below:

    <?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Project extends Model
    {
        /**
         * {@inheritDoc}
         */
        protected $fillable = ['name', 'user_id'];

        /**
        * {@inheritDoc}
        */
        protected $with = ['user'];

        /**
         * Get associated user.
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
         */
        public function user()
        {
            return $this->belongsTo(User::class);
        }

        /**
         * Get associated timers.
         *
         * @return \Illuminate\Database\Eloquent\Relations\HasMany
         */
        public function timers()
        {
            return $this->hasMany(Timer::class);
        }

        /**
         * Get my projects
         *
         * @param  \Illuminate\Database\Eloquent\Builder $query
         * @return \Illuminate\Database\Eloquent\Builder
         */
        public function scopeMine($query)
        {
            return $query->whereUserId(auth()->user()->id);
        }
    }

In the Eloquent model above, we define the fillables, and the with array used to specify relationships to eagerly load.

We define the user relationship, which says a project belongs to one User. We also define a timers relationship which says every project has many Timers.

Finally, we define an Eloquent Query Scope in the scopeMine method. Query scopes make it easier to mask complex queries in an Eloquent model. The scopeMine is supposed to add the where a query that restricts the projects to only those belonging to the current user.

The next file will be the ProjectController. Open the controller file, ./app/Http/ProjectController.php, and paste the following code:

    <?php
    namespace App\Http\Controllers;

    use App\Project;
    use Illuminate\Http\Request;

    class ProjectController extends Controller
    {
        public function __construct()
        {
            $this->middleware('auth');
        }

        public function index()
        {
            return Project::mine()->with('timers')->get()->toArray();
        }

        public function store(Request $request)
        {
            // returns validated data as array
            $data = $request->validate(['name' => 'required|between:2,20']);

            // merge with the current user ID
            $data = array_merge($data, ['user_id' => auth()->user()->id]);

            $project = Project::create($data);

            return $project ? array_merge($project->toArray(), ['timers' => []]) : false;
        }
    }

In the controller above, we define the middleware auth so that only authenticated users can access methods on the controller.

In the index method, we return all the projects belonging to the logged in user. By adding with('timers') we eager load the timers relationship. In the store method, we just create a new Project for the user.

Creating Our Timer Database Migration, Model and Controller
The next set of components to edit will be the Timer. Open the timer migration file *_create_timers_table.php and paste the following in the file:

    <?php

    use Illuminate\Support\Facades\Schema;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;

    class CreateTimersTable extends Migration
    {
        public function up()
        {
            Schema::create('timers', function (Blueprint $table) {
                $table->increments('id');
                $table->string('name');
                $table->unsignedInteger('project_id');
                $table->unsignedInteger('user_id');
                $table->timestamp('started_at');
                $table->timestamp('stopped_at')->default(null)->nullable();
                $table->timestamps();

                $table->foreign('user_id')->references('id')->on('users');
                $table->foreign('project_id')->references('id')->on('projects');
            });
        }

        public function down()
        {
            Schema::dropIfExists('timers');
        }
    }

Next, we will update the Timer model. Open the class and, in the file, paste the following code:

    <?php
    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Timer extends Model
    {
        /**
         * {@inheritDoc}
         */
        protected $fillable = [
          'name', 'user_id', 'project_id', 'stopped_at', 'started_at'
        ];

        /**
        * {@inheritDoc}
        */
        protected $dates = ['started_at', 'stopped_at'];

        /**
         * {@inheritDoc}
         */
        protected $with = ['user'];

        /**
         * Get the related user.
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
         */
        public function user()
        {
            return $this->belongsTo(User::class);
        }

        /**
         * Get the related project
         *
         * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
         */
        public function project()
        {
            return $this->belongsTo(Project::class);
        }

        /**
         * Get timer for current user.
         *
         * @param  \Illuminate\Database\Eloquent\Builder $query
         * @return \Illuminate\Database\Eloquent\Builder
         */
        public function scopeMine($query)
        {
            return $query->whereUserId(auth()->user()->id);
        }

        /**
         * Get the running timers
         *
         * @param  \Illuminate\Database\Eloquent\Builder $query
         * @return \Illuminate\Database\Eloquent\Builder
         */
        public function scopeRunning($query)
        {
            return $query->whereNull('stopped_at');
        }
    }

In the model above, we defined two relationships. The first is user which states that the timer belongs to one User. The second relationship is the project relationship which states that a Timer belongs to a Project.

We also define two query scopes, the scopeMine which adds where a query for all the timers belonging to the user, and the scopeRunning which adds a where a query for all timers that are running.

Next, let’s update the TimerController too. Paste the code below in the controller:

    <?php
    namespace App\Http\Controllers;

    use App\Timer;
    use App\Project;
    use Carbon\Carbon;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;

    class TimerController extends Controller
    {
        public function store(Request $request, int $id)
        {
            $data = $request->validate(['name' => 'required|between:3,100']);

            $timer = Project::mine()->findOrFail($id)
                                    ->timers()
                                    ->save(new Timer([
                                        'name' => $data['name'],
                                        'user_id' => Auth::user()->id,
                                        'started_at' => new Carbon,
                                    ]));

            return $timer->with('project')->find($timer->id);
        }

        public function running()
        {
            return Timer::with('project')->mine()->running()->first() ?? [];
        }

        public function stopRunning()
        {
            if ($timer = Timer::mine()->running()->first()) {
                $timer->update(['stopped_at' => new Carbon]);
            }

            return $timer;
        }
    }

In the controller above, we have defined the store method. This method just creates a new timer and associates it with the loaded project.

The next method called running just returns active timers belonging to the current user. The final method is the stopRunning. It stops the actively running timer belonging to the current user.

Connecting to a Database
Next, we will connect our application to a Database. To do this, update the values of the DB_* keys in the .env file. To keep this application simple, we will be using the SQLite database driver.

Open the .env file and replace the values:

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=homestead
    DB_USERNAME=homestead
    DB_PASSWORD=secret

with:

    DB_CONNECTION=sqlite 

Next, create an empty file in the databases directory named database.sqlite. That’s all. Your application is ready to use SQLite as it’s database.

To execute the available migrations we created earlier, run the following command on the terminal:

    $ php artisan migrate

Here is a sample response we will get after running the command:

Adding Authentication To Our Laravel Application
Next, let us add some authentication. To add authentication to our current project, run the command below in your terminal:

    $ php artisan make:auth

After running this article, a couple of files will be added to our project automatically. However, we don’t need to bother about them. That’s all for adding authentication.

Adding the Appropriate Routes
Since we have created our controllers, let’s create routes that point to the methods in them. Open the routes/web.php file and replace the content with the following:

    <?php

    Auth::routes();
    Route::redirect('/', '/home');
    Route::get('/home', 'HomeController@index')->name('home');
    Route::get('/projects', 'ProjectController@index');
    Route::post('/projects', 'ProjectController@store');
    Route::post('/projects/{id}/timers/stop', 'TimerController@stopRunning');
    Route::post('/projects/{id}/timers', 'TimerController@store');
    Route::get('/project/timers/active', 'TimerController@running');

On line 3 we have the Auth::routes(). Also, we have defined additional routes that will be useful for our application.

Setting Up Our Vue Application

When working with Vue in Laravel, you can either start from an entirely new application or use the in-built Vue integration. We will do the latter. In the terminal, run the command below to install the NPM dependencies:

    $ npm install

After the dependencies have been installed, you can run the command below to build your assets manually every time you make a change:

    $ npm run dev

💡 You can run **npm run watch** to start Laravel mix with automatic compiling of assets.

Creating Our Application’s Entry Point

The first thing we want to create is an entry point to our Vue application. The entry point will be the page that shows up immediately after a user logs in.

Before we continue, start a PHP server using Artisan by running the command below in a new terminal tab:

    $ php artisan serve

This should make your application available on this URL: http://127.0.0.1:8000. Visit the URL and create a new account. When you have created an account, you will be automatically logged in and you should see a “Dashboard”. Let us use this as our Vue entry point.

Open the view that is responsible for this page, resources/views/home.blade.php, and paste in the following code:

    @extends('layouts.app')

    @section('content')
    <div class="container">
        <div class="row">
            <dashboard></dashboard>
        </div>
    </div>
    @endsection

In the above, we have introduced a Vue component called dashboard. Let us create that component in Vue.

Open the resources/assets/js/app.js file and replace the contents with the following code:

    // Load other dependencies
    require('./bootstrap');

    // Load Vue
    window.Vue = require('vue');

    // Vue components!
    Vue.component('dashboard', require('./components/DashboardComponent.vue'));

    // Create a Vue instance
    const app = new Vue({el: '#app'});

In the code above, we register a new Vue component called dashboard and include it from the ./components/DashboardComponent.vue file. Create that file and let’s build out our Vue component.

In the file, we will divide the process into template and script. The template will be the Vue HTML part and the script will be the Vue JavaScript.

Let’s create the Vue HTML part. In the file paste in the following code:

    <template>
        <div class="col-md-8 col-md-offset-2">
            <div class="no-projects" v-if="projects">

                <div class="row">
                    <div class="col-sm-12">
                        <h2 class="pull-left project-title">Projects</h2>
                        <button class="btn btn-primary btn-sm pull-right" data-toggle="modal" data-target="#projectCreate">New Project</button>
                    </div>
                </div>

                <hr>

                <div v-if="projects.length > 0">
                    <div class="panel panel-default" v-for="project in projects" :key="project.id">
                        <div class="panel-heading clearfix">
                            <h4 class="pull-left">{{ project.name }}</h4>

                            <button class="btn btn-success btn-sm pull-right" :disabled="counter.timer" data-toggle="modal" data-target="#timerCreate" @click="selectedProject = project">
                                <i class="glyphicon glyphicon-plus"></i>
                            </button>
                        </div>

                        <div class="panel-body">
                            <ul class="list-group" v-if="project.timers.length > 0">
                                <li v-for="timer in project.timers" :key="timer.id" class="list-group-item clearfix">
                                    <strong class="timer-name">{{ timer.name }}</strong>
                                    <div class="pull-right">
                                        <span v-if="showTimerForProject(project, timer)" style="margin-right: 10px">
                                            <strong>{{ activeTimerString }}</strong>
                                        </span>
                                        <span v-else style="margin-right: 10px">
                                            <strong>{{ calculateTimeSpent(timer) }}</strong>
                                        </span>
                                        <button v-if="showTimerForProject(project, timer)" class="btn btn-sm btn-danger" @click="stopTimer()">
                                            <i class="glyphicon glyphicon-stop"></i>
                                        </button>
                                    </div>
                                </li>
                            </ul>
                            <p v-else>Nothing has been recorded for "{{ project.name }}". Click the play icon to record.</p>
                        </div>
                    </div>
                    <!-- Create Timer Modal -->
                    <div class="modal fade" id="timerCreate" role="dialog">
                        <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal">×</button>
                                    <h4 class="modal-title">Record Time</h4>
                                </div>
                                <div class="modal-body">
                                    <div class="form-group">
                                        <input v-model="newTimerName" type="text" class="form-control" id="usrname" placeholder="What are you working on?">
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button data-dismiss="modal" v-bind:disabled="newTimerName === ''" @click="createTimer(selectedProject)" type="submit" class="btn btn-default btn-primary"><i class="glyphicon glyphicon-play"></i> Start</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-else>
                    <h3 align="center">You need to create a new project</h3>
                </div>
                <!-- Create Project Modal -->
                <div class="modal fade" id="projectCreate" role="dialog">
                    <div class="modal-dialog modal-sm">
                        <div class="modal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal">×</button>
                                <h4 class="modal-title">New Project</h4>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <input v-model="newProjectName" type="text" class="form-control" id="usrname" placeholder="Project Name">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button data-dismiss="modal" v-bind:disabled="newProjectName == ''" @click="createProject" type="submit" class="btn btn-default btn-primary">Create</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="timers" v-else>
                Loading...
            </div>
        </div>
    </template> 

In the template we create a New Project button which loads up a #projectCreate Bootstrap modal. The modal contains a form that adds a new project when the submit button is clicked.

In there we loop through the projects array in Vue and, in that loop, we loop through each of the project’s timers and display them. We have also defined a few buttons such as the stop timer button and the add timer button which stops the timer or adds a new timer to the stack.

In the same file, paste this at the bottom of the file right after the closing template tag:

    <script>
    import moment from 'moment'
    export default {
        data() {
            return {
                projects: null,
                newTimerName: '',
                newProjectName: '',
                activeTimerString: 'Calculating...',
                counter: { seconds: 0, timer: null },
            }
        },
        created() {
            window.axios.get('/projects').then(response => {
                this.projects = response.data
                window.axios.get('/project/timers/active').then(response => {
                    if (response.data.id !== undefined) {
                        this.startTimer(response.data.project, response.data)
                    }
                })
            })
        },
        methods: {
            /**
             * Conditionally pads a number with "0"
             */
            _padNumber: number =>  (number > 9 || number === 0) ? number : "0" + number,

            /**
             * Splits seconds into hours, minutes, and seconds.
             */
            _readableTimeFromSeconds: function(seconds) {
                const hours = 3600 > seconds ? 0 : parseInt(seconds / 3600, 10)
                return {
                    hours: this._padNumber(hours),
                    seconds: this._padNumber(seconds % 60),
                    minutes: this._padNumber(parseInt(seconds / 60, 10) % 60),
                }
            },

            /**
             * Calculate the amount of time spent on the project using the timer object.
             */
            calculateTimeSpent: function (timer) {
                if (timer.stopped_at) {
                    const started = moment(timer.started_at)
                    const stopped = moment(timer.stopped_at)
                    const time = this._readableTimeFromSeconds(
                        parseInt(moment.duration(stopped.diff(started)).asSeconds())
                    )
                    return `${time.hours} Hours | ${time.minutes} mins | ${time.seconds} seconds`
                }
                return ''
            },

            /**
             * Determines if there is an active timer and whether it belongs to the project
             * passed into the function.
             */
            showTimerForProject: function (project, timer) {
                return this.counter.timer &&
                       this.counter.timer.id === timer.id &&
                       this.counter.timer.project.id === project.id
            },

            /**
             * Start counting the timer. Tick tock.
             */
            startTimer: function (project, timer) {
                const started = moment(timer.started_at)

                this.counter.timer = timer
                this.counter.timer.project = project
                this.counter.seconds = parseInt(moment.duration(moment().diff(started)).asSeconds())
                this.counter.ticker = setInterval(() => {
                    const time = this._readableTimeFromSeconds(++vm.counter.seconds)

                    this.activeTimerString = `${time.hours} Hours | ${time.minutes}:${time.seconds}`
                }, 1000)
            },

            /**
             * Stop the timer from the API and then from the local counter.
             */
            stopTimer: function () {
                window.axios.post(`/projects/${this.counter.timer.id}/timers/stop`)
                            .then(response => {
                                // Loop through the projects and get the right project...
                                this.projects.forEach(project => {
                                    if (project.id === parseInt(this.counter.timer.project.id)) {
                                        // Loop through the timers of the project and set the `stopped_at` time
                                        return project.timers.forEach(timer => {
                                            if (timer.id === parseInt(this.counter.timer.id)) {
                                                return timer.stopped_at = response.data.stopped_at
                                            }
                                        })
                                    }
                                });

                                // Stop the ticker
                                clearInterval(this.counter.ticker)

                                // Reset the counter and timer string
                                this.counter = { seconds: 0, timer: null }
                                this.activeTimerString = 'Calculating...'
                            })
            },

            /**
             * Create a new timer.
             */
            createTimer: function (project) {
                window.axios.post(`/projects/${project.id}/timers`, {name: this.newTimerName})
                            .then(response => {
                                project.timers.push(response.data)
                                this.startTimer(response.data.project, response.data)
                            })

                this.newTimerName = ''
            },

            /**
             * Create a new project.
             */
            createProject: function () {
                window.axios.post('/projects', {name: this.newProjectName})
                            .then(response => this.projects.push(response.data))

                this.newProjectName = ''
            }
        },
    }
    </script>

In the Vue component script above we have started by declaring the data variables. We will be referring to them in the script and template sections of the component.

We have implemented a created method which is called automatically when the Vue component is created. Inside it we make a GET request to /projects, load up all the projects and assign them to the projects variable. We also check if there is an active timer and, if there is, we start it using the startTimer method.

Next, in the methods object, we define a couple of methods that will be available all around our Vue component. The components are well commented and each of them distinctively tells what they do.

In the startTimer method, we start a timer based on the started_at property of the time. In the stopTimer method, we send a request to the API and then stop the timer locally by calling clearInterval on the saved timer instance.

We also have a createProject and a createTimer method. These do just what they say by sending an API request to the Laravel backend and then adding the project/timer to the list of existing ones in Vue.

If you noticed, at the beginning of the script we tried to import Moment but we have not added it to our NPM dependencies. To do this run the command below:

    $ npm install --save moment

Now rebuild your assets using the code below:

    $ npm run dev

With the changes you can now load the page. You can create a PHP server using Artisan if you haven’t already done so using the code below:

    $ php artisan serve

You should now see your web application.

Conclusion

With the power of Laravel and Vue, you can create really modern web applications really quickly and this has demonstrated how quickly you can harness both technologies to create amazing applications.

Hopefully, you have learned a thing or two from the tutorial. If you have any questions or feedback please leave them below in the comment section.

The source code to the application in this article is available on GitHub.