PHPackages                             alvin0/database-json-laravel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. alvin0/database-json-laravel

ActiveLibrary[Database &amp; ORM](/categories/database)

alvin0/database-json-laravel
============================

Create and manage json databases with Laravel

2.1.2(5y ago)344.5k↑61.5%9[2 issues](https://github.com/alvin0/database-json-laravel/issues)[1 PRs](https://github.com/alvin0/database-json-laravel/pulls)MITPHPPHP ^7.2|^8.0CI failing

Since Dec 15Pushed 2y ago1 watchersCompare

[ Source](https://github.com/alvin0/database-json-laravel)[ Packagist](https://packagist.org/packages/alvin0/database-json-laravel)[ Docs](https://github.com/alvin0/DatabaseJsonLaravel)[ RSS](/packages/alvin0-database-json-laravel/feed)WikiDiscussions master Synced yesterday

READMEChangelog (6)Dependencies (2)Versions (11)Used By (0)

Database Json Laravel - php flat file database based on JSON files Library to use JSON files like a database. Functionality inspired by Eloquent

Requirements
------------

[](#requirements)

- PHP 7.2.5+
- Composer

Installation
------------

[](#installation)

You can install the package via composer

```
composer require alvin0/database-json-laravel

```

Optional: The service provider will automatically get registered. Or you may manually add the service provider in your `config/app.php` file:

```
'providers' => [
    // ...
    DatabaseJson\DataBaseJsonServiceProvider::class,
];

```

You should publish the `config/databasejson.php` config file .

Structure of table files
------------------------

[](#structure-of-table-files)

`table_name.data.json` - table file with data `table_name.config.json` - table file with configuration

Basic Usage
-----------

[](#basic-usage)

### I. Create Model and Migration with command line

[](#i-create-model-and-migration-with-command-line)

#### 1. Model

[](#1-model)

##### Create model :

[](#create-model-)

```
php artisan databasejson:model User -m

```

##### Optional :

[](#optional-)

```
 -m  : Generate a migrate for the given model.
 -f : Create the class even if the model already exists

```

##### Code generate

[](#code-generate)

```
namespace  App\DatabaseJson\Models;

use DatabaseJson\Model;

class User extends  Model
{

}
```

#### 2. Migration

[](#2-migration)

##### 2.1 Create a migration table

[](#21-create-a-migration-table)

```
php artisan databasejson:migration user --table=users

```

##### Code generate

[](#code-generate-1)

```
namespace  App\DatabaseJson\Migrations;

use DatabaseJson\DatabaseJson;
use DatabaseJson\Migration;

class CreateTableUserMigrateMigrate extends  Migration
{
	/**
	* How to create table
	*
	* DatabaseJson::table('NameTable',array(
	* {field_name} => {field_type} More information about field types and usage in PHPDoc
	* ));
	*/
	/**
	* Run the migrations.
	*
	* @return  void
	*/

	public  function  up()
	{
		DatabaseJson::create('users', array(
			'name' => 'string',
			'old' => 'integer',
			'created_at' => 'string',
			'updated_at' => 'string',
		));
	}

}
```

##### Optional

[](#optional)

The --table option may also be used to indicate the name of the table. the --update option will create migrate with method update table

##### 2.2 Update migrate table

[](#22-update-migrate-table)

The update only supports adding or removing columns in the table

If you want to delete the table, use this method in the function up() :

```
DatabaseJson::remove('table_name');

```

##### example create migrate type update

[](#example-create-migrate-type-update)

```
php artisan databasejson:migration user --table="users" --update

```

##### Code generate

[](#code-generate-2)

```
namespace  App\DatabaseJson\Migrations;

use DatabaseJson\DatabaseJson;
use DatabaseJson\Migration;

class CreateTableUserMigrateMigrate extends  Migration
{
	/**
	* Run the migrations.
	*
	* @return  void
	*/
	public  function  up()
	{
		DatabaseJson::table('users')->addFields([
			//'name' => 'string'
			//{field_name} => {field_type} More information about field types and usage in PHPDoc
		]);

		//DatabaseJson::table('users')->deleteFields([
			//'name',
			//{field_name}
		//]);
	}

}
```

##### 2.3 Run Migrate

[](#23-run-migrate)

```
php artisan databasejson:migrate

```

##### Optional

[](#optional-1)

\--fresh : remove all table and up --path : Specify a path

### II. Basic Usage

[](#ii-basic-usage)

#### 1. Model Conventions

[](#1-model-conventions)

By default, model expects `created_at` and `updated_at` columns to exist on your tables. If you do not wish to have these columns automatically managed by Model, set the `$timestamps` property on your model to `false`:

```
namespace  App\DatabaseJson\Models;

use DatabaseJson\Model;

class User extends  Model
{
	/**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

}
```

#### 2. Inserting &amp; Updating &amp; Delete Models

[](#2-inserting--updating--delete-models)

##### 2.1 Insert

[](#21-insert)

To create a new record in the database, create a new model instance, set attributes on the model, then call the `save` or use static function `create` method:

```
use App\DatabaseJson\Models\User;

$user = new User;
$user->name = 'alvin';
$user->old = 27;
$user->save();
```

Example

```
use App\DatabaseJson\Models\User;

$user = User::create([
	'name' => 'alvin',
	'old' => 27
]);
```

##### 2.2 Update

[](#22-update)

To create a new record in the database, create a new model instance, set attributes on the model, then call the `save` or use static function `create` method:

```
use App\DatabaseJson\Models\User;

$user = new User;
$user->id = 1;
$user->name = 'alvin';
$user->old = 27;
$user->save();
```

Example

```
use App\DatabaseJson\Models\User;

$id = 1;
$user = User::update([
	'name' => 'alvin',
	'old' => 28
],$id);
```

##### 2.3 Delete

[](#23-delete)

Remove data with constraints

```
use App\DatabaseJson\Models\User;

$id = 1;
$user = User::where('name','alvin')->delete();
$userById = User::find(1)->delete();
```

Remove all data in table

```
use App\DatabaseJson\Models\User;

$id = 1;
$user = User::delete();
```

#### 3. Retrieving Models

[](#3-retrieving-models)

```
all() -> This is a static function used to retrieve all objects in the model.
find($id) -> This is a static function used to retrieve an object by id in the model.

```

Adding Additional Constraints

You may add constraints to queries, and then use the `get()` or `paginate($perpage)` method to retrieve the results

```
where() - filter records ( Standard operators =, !=, >, =, where('old', '>=', 18)
   ->get();
```

- use `paginate($perpage)` retrieve the results

```
use App\DatabaseJson\Models\User;

$users = User::paginate(10);
```

- add constraints

```
use App\DatabaseJson\Models\User;

$users = User::where('old', '>=', 18)->paginate(10);
```

#### 4 Relations

[](#4-relations)

##### 4.1 setup relationship

[](#41-setup-relationship)

There are 2 relationships when applied : belongsTo and hasMany

local\_key default is `id`

- belongsTo foreign\_key default is `primaryKey` table relation

```
return $this->belongsTo('App\DatabaseJson\Models\User', 'local_key', 'foreign_key');
```

```
namespace  App\DatabaseJson\Models;

use DatabaseJson\Model;

class Blog extends  Model
{
	public  function  user()
	{
		$this->belongsTo(User::class);
	}

}
```

- hasMany

```
return $this->hasMany('App\DatabaseJson\Models\Blog', 'foreign_key', 'local_key');
```

```
namespace  App\DatabaseJson\Models;

use DatabaseJson\Model;

class User extends  Model
{
	public  function  blogs()
	{
		return  $this->hasMany(Blog::class, 'user_id');
	}

}
```

##### 4.2 Retrieve relationship

[](#42-retrieve-relationship)

- belongsTo

```
	//return model App\DatabaseJson\Models\User
	$userBlog = Blog::find(1)->user
```

- hasMany

```
	//return Illuminate\Support\Collection
	$blogsByUser = User::find(1)->blogs
```

- Appends relational data to model results when retrieved with function `with()`

```
	$users = User::with('blogs')->where('id', 1)->get();
```

#### 5 creating the accessor

[](#5-creating-the-accessor)

##### 5.1Defining An Accessor

[](#51defining-an-accessor)

To define an accessor, create a getFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the first\_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first\_name attribute:

```
