Easily set up a sync endpoint to support Watermelon DB in your Laravel projects.

Overview

Laravel Watermelon

This package provides a Watermelon DB backend sync implementation for Laravel. Watermelon DB is a robust local database synchronization tool to help develop offline-first application. One of the biggest hurdles is implementing the logic on your server to handle the synchronization process.

That's where this package comes in to provide a quick synchronization route you can get up and running in minutes.

This project is still in active development and does not support schema versions or migrations yet. Both of these are major parts of the Watermelon DB spec. Please expect large changes at least until those features are implemented.

Installation

Before getting started you'll need to install the package and publish the config file.

composer require nathanheffley/laravel-watermelon
php artisan vendor:publish --tag="watermelon-config"

Usage

Once you've installed the package, you need to specify which models will be available through the synchronization endpoint. Open up the config/watermelon.php file and update the models array. The key needs to be the name of table used locally in your application, and the value must be classname of the related model.

You can also change the route to be something other than /sync by editing the config file or setting the WATERMELON_ROUTE environment variable. You will have to ensure your application makes synchronization requests to whatever route you specify.

By default, only your global middleware will be applied to the synchronization endpoint. This means that unless you changed the default global middleware in your Laravel project the synchronization endpoint will be unauthenticated. If you want to have access to the currently authenticated user you will need to add the web middleware to the config file's middleware array. If you want to restrict access to the synchronization endpoint to authenticated users only, you can add the auth middleware in addition to the web middleware. Of course, you can add any middleware you would like as long as it's registered in your project.

<?php

use App\Models\Project;
use App\Models\Task;

return [

    'route' => env('WATERMELON_ROUTE', '/watermelon'),
    
    'middleware' => [
        'web',
        'auth',
    ],

    'models' => [
         'projects' => Project::class,
         'tasks' => Task::class,
    ],

];

Once you've specified which models should be available through the synchronization endpoint, you'll need to implement some functionality in the models to support being served as Watermelon change objects.

You will need to add a database column to all of your models to keep track of what the Watermelon ID is, called watermelon_id. The default IDs generated by Watermelon are alphanumeric strings, although you can change the type of the column if you don't use the default IDs autogenerated by Watermelon. A unique index on the column is recommended, and I like placing it directly after the id column.

<?php

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

class AddWatermelonIdToTasksTable extends Migration
{
    public function up()
    {
        Schema::table('tasks', function (Blueprint $table) {
            $table->string('watermelon_id')->after('id')->unique();
        });
    }

    public function down()
    {
        Schema::table('tasks', function (Blueprint $table) {
            $table->dropColumn('watermelon_id');
        });
    }
}

If you did not originally include the created_at, updated_at, and deleted_at timestamp columns, you will also need to add those columns. Please refer to the Laravel documentation for implementing the timestamps and soft deleting functionality.

The only thing you must change in your model class is to use the Watermelon trait.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use NathanHeffley\LaravelWatermelon\Traits\Watermelon;

class Task extends Model
{
    use SoftDeletes, Watermelon;
}

The attributes returned through the synchronization endpoint are whitelisted by default. Out of the box, only the watermelon_id will be returned (although it will be passed through the endpoint as just id, this is intentional). To include more attributes, you will need to add a watermelonAttributes property to your class. These attributes will be included alongside the Watermelon ID and can be updated by change objects posted to the synchronization endpoint.

class Task extends Model
{
    use SoftDeletes, Watermelon;

    protected array $watermelonAttributes = [
        'content',
        'is_completed',
    ];
}

If you need more control over the attributes returned you can override the entire toWatermelonArray function.

Authorization

By default, all models will be accessible and able to be updated through the synchronization endpoint. This is obviously not ideal in most projects where you need control to authorize which models users can see and what they can update.

Scoping entire records

You can implement a query scope on your models by overriding the scopeWatermelon function. This scope will be applied before returning data to pull requests. This can be used, for example, to restrict records to only be retrievable by users authorized to see them (to have access to the Auth::user() like in this example, don't forget to add the web and auth middlewares as shown in the config example at the start of the Usage section).

use Illuminate\Support\Facades\Auth;

class Task extends Model
{
    // ...

    public function scopeWatermelon($query)
    {
        return $query->where('user_id', Auth::user()->id);
    }
}

Package Development

If you have PHP and Composer installed on your local machine you should be able to easily run the PHPUnit test suite.

If you prefer to run the tests within a Docker container, this project includes Laravel Sail.

To install the dependencies:

docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v $(pwd):/opt \
    -w /opt \
    laravelsail/php80-composer:latest \
    composer install --ignore-platform-reqs

To run the test suite:

sail exec laravel.test ./vendor/bin/phpunit
You might also like...
Quickly generate pivot tables for your projects
Quickly generate pivot tables for your projects

Laravel Pivot Table Generator Quickly generate pivot tables for your projects! Table of Contents Installation Usage More generator packages Contributi

A Laravel Wrapper for the CoinDCX API. Now easily connect and consume the CoinDCX Public API in your Laravel apps without any hassle.
A Laravel Wrapper for the CoinDCX API. Now easily connect and consume the CoinDCX Public API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the CoinDCX API and allows you to easily communicate with it. Important Note This package is in early deve

Easily add a full Laravel blog (with built in admin panel and public views) to your laravel project with this simple package.

Webdevetc BlogEtc - Complete Laravel Blog Package Quickly add a blog with admin panel to your existing Laravel project. It has everything included (ro

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

Laravel comments - This package enables to easily associate comments to any Eloquent model in your Laravel application

A set of useful Laravel collection macros
A set of useful Laravel collection macros

A set of useful Laravel collection macros This repository contains some useful collection macros. Spatie is a webdesign agency based in Antwerp, Belgi

⛽ Set of utilities to test Laravel applications powered by Octane.

⛽ Octane Testbench Set of utilities to test Laravel applications powered by Octane. Install Via Composer: composer require --dev cerbero/octane-testbe

This package gives you a set of conventions to make the most out of Hotwire in Laravel

Introduction This package gives you a set of conventions to make the most out of Hotwire in Laravel (inspired by the turbo-rails gem). There is a comp

Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application.

Laracademy Generators Laracademy Generators - is a tool set that helps speed up the development process of a Laravel application. Author(s): Laracadem

Laravel package for giving admin-created accounts to users via 'set-password' email.

Invytr When making a website where users are created instead of registering themselves, you are faced with the challenge of safely giving users the ac

Comments
  • Watermelon_ID Not Syncing to Backend DB

    Watermelon_ID Not Syncing to Backend DB

    I have implemented your sync adapter and doing some tests with my react-native app. I cannot get the watermelon_id to populate in my MySQL database. Maybe I am not understanding how this works. I have a sync button in my app that successfully pulls the data from my backend database to WatermelonDB. But if I change anything on the backend and try to sync it does not update the data on the app. Am I missing something? Thanks much!

    opened by doobe01 4
  • Link Watermelon demos in README

    Link Watermelon demos in README

    @doobe01 pointed out that the nathanheffley/laravel-watermelom-demos isn't linked in the README anywhere. A link to that repo should definitely be added near the top of the README.

    opened by nathanheffley 0
Releases(v0.0.1)
  • v0.0.1(Aug 8, 2021)

    This is the initial release, with only the bear minimum needed to support a rudimentary Watermelon DB application.

    Schema Versioning and Migrations are not implemented at all currently. Only pulling and pushing records is supported.

    This release is not ready for production. Please only use this if you know what you're doing or wish to contribute to making this package fully featured.

    Source code(tar.gz)
    Source code(zip)
Owner
Nathan Heffley
PHP and JavaScript developer. Developing internal tools @dealerinspire and running @lancasterlaravel
Nathan Heffley
Postier is a Laravel API automation platform to transfer data and to sync apps.

Postier is a Laravel API automation platform to transfer data and to sync apps. You can build workflows with data and actions of multiple apps and apply logics to the data!

null 55 Oct 28, 2022
Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App.

OvalFi Laravel Package Laravel-OvalFi helps you Set up, test, and manage your OvalFi integration directly in your Laravel App. Installation You can in

Paul Adams 2 Sep 8, 2022
Llum illuminates your Laravel projects speeding up your Github/Laravel development workflow

Llum illuminates your Laravel projects speeding up your Github/Laravel development workflow

Sergi Tur Badenas 110 Dec 25, 2022
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
Cagilo - a set of simple components for use in your views Laravel Blade.

Cagilo - a set of simple components for use in your views Laravel Blade. Official Documentation Documentation for Cagilo can be found on its we

Cagilo 151 Dec 6, 2022
This Laravel 8 package makes it possible for you to set your website in "Under Construction" mode.

Laravel Under Construction This Laravel package makes it possible to set your website in "Under Construction" mode. Only users with the correct 4 digi

Lars Janssen 571 Dec 18, 2022
Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views

Blade UI Kit is a set of renderless components to utilise in your Laravel Blade views. In all essence, it's a collection of useful utilities, connecting the dots between different parts of the TALL stack. It was made for Blade, Laravel's powerful templating engine.

Blade UI Kit 1.2k Jan 5, 2023
👀 Manage your views in Laravel projects through artisan

Artisan View This package adds a handful of view-related commands to Artisan in your Laravel project. Generate blade files that extend other views, sc

Sven Luijten 842 Dec 29, 2022
Easy-to-use SDK for implementing Neshan APIs in your Laravel projects.

Neshan Laravel SDK Easy-to-use SDK for implementing Neshan APIs in your Laravel projects. Install The easiest way to install is by using Composer: com

null 1 Oct 22, 2022
A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic

A light weight laravel package that facilitates dealing with arabic concepts using a set of classes and methods to make laravel speaks arabic! concepts like , Hijri Dates & Arabic strings and so on ..

Adnane Kadri 49 Jun 22, 2022