PHPackages                             sansu/save-model - 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. sansu/save-model

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

sansu/save-model
================

Just a new way to save data in the database

07PHP

Since Dec 31Pushed 4y ago1 watchersCompare

[ Source](https://github.com/zunyru/sansu)[ Packagist](https://packagist.org/packages/sansu/save-model)[ RSS](/packages/sansu-save-model/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

Save Model
==========

[](#save-model)

Save Model is a Laravel package that allows you to save data in the database in a new way. No need to worry about `$guarded` and `$fillable` properties in the model anymore. Just relax an use `Save Model` package.

---

[![Latest Version on Packagist](https://camo.githubusercontent.com/f71a5a4eb492deb16d6d46dde48e11e8b5ad8c68404421d9d3064e2eb3bdb99c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617364682f736176652d6d6f64656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/asdh/save-model)[![GitHub Tests Action Status](https://camo.githubusercontent.com/fc7d4e1fc6c855a16d27f75f695766c2f6793107cc83a871d2067c24d3cfa7a0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f617364682f736176652d6d6f64656c2f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/asdh/save-model/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/c421290688d432fe035ff9ca600232b07aa0a424374f21c3a57deac649f5b714/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f617364682f736176652d6d6f64656c2f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/asdh/save-model/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/dcfb96ff701bebe1d952d991aa1160b6f1c549eea69fc1c5570974f4a03d1d59/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f617364682f736176652d6d6f64656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/asdh/save-model)

---

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

[](#installation)

You can install the package via composer:

```
composer require sansu/save-model
```

You can publish the config file with:

```
php artisan save-model:publish

or

php artisan vendor:publish --provider="Asdh\SaveModel\SaveModelServiceProvider"
```

This is the contents of the published config file:

```
// config/save_model.php

return [
    /**
     * The directory name where the files should be stored
     * This can be changed via 'saveableFields' method on model
     */
    'file_upload_directory' => 'files',
];
```

Usage
-----

[](#usage)

```
// In controller

use Asdh\SaveModel\SaveModel;

SaveModel::new(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

// OR

(new SaveModel(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();
```

You just do this and a new user will be created and saved to the 'users' table. The password will be automatically hashed, and uploading of the image will also be automatically handled.

To update a model, you just have to pass the model that you want to update.

```
// In controller

use Asdh\SaveModel\SaveModel;

$user = User::find(1);

SaveModel::new(
    $user,
    $request->only(['name', 'email'])
)->execute();
```

Only name and email will be updated and no other columns will be touched.

**For this to work, you need to do these things:**

Go to User model class or any other model class and add `CanBeSavedContract` class to it. In this example, I will use User model.

```
use Asdh\SaveModel\Contracts\CanBeSavedContract;

class User extends Authenticatable implements CanBeSavedContract
{

}
```

After adding this, you need to add `saveableFields` method to the User model and map every columns of the users table like so:

```
use Asdh\SaveModel\Contracts\CanBeSavedContract;
use Asdh\SaveModel\Fields\DatetimeField;
use Asdh\SaveModel\Fields\FileField;
use Asdh\SaveModel\Fields\PasswordField;
use Asdh\SaveModel\Fields\StringField;

class User extends Authenticatable implements CanBeSavedContract
{
    public function saveableFields(): array
    {
        return [
            'name' => StringField::new(),
            'email' => StringField::new(),
            'email_verified_at' => DatetimeField::new(),
            'password' => PasswordField::new(),
            'image' => FileField::new(),
        ];
    }
}
```

After doing this you are good to go. In the controller, you just need to get the data and use the `SaveModel` class

```
use Asdh\SaveModel\SaveModel;

SaveModel::new(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();

// OR

(new SaveModel(
    new User,
    $request->only(['name', 'email', 'password', 'image'])
)->execute();
```

The files will be uploaded using the default `Laravel's filesystem`. Which means that you can directly configure to upload the files directly to the `S3` as well or any other that Laravel supports.

Also, the files will be uploaded to the `files` directory by default. You can change that globally by changing the value of `file_upload_directory` on the `save_model.php` configuration file.

You can also change it per model like so:

```
// app/Models/User.php

public function saveableFields(): array
{
    return [
        'image' => FileField::new()->setDirectory('images'),
    ];
}
```

It will now store the `image` of the user to the `images` directory and for every other `Models`, it will use from the `save_model.php` config file.

You can also, choose the Laravel Filesystem's `disk` per model like so:

```
// app/Models/User.php

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->setDisk('s3'),
    ];
}
```

By default `random name` will be generated for the uploaded files, but you can change that also. You just have to pass closure on the `setFileName` method and you will get access to the uploaded file there. And whatever you return from here will be saved to the database as the file name.

This example shows how to return the original file name.

```
// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->setFileName(function (UploadedFile $uploadedFile) {
                return $uploadedFile->getClientOriginalName();
            }),
    ];
}
```

If you want to upload the file as the original name then you can do this:

```
// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->uploadAsOriginalName(),
    ];
}
```

One thing to keep in mind that the `setFileName` method will take precedence over `uploadAsOriginalName` if both methods are being used.

Not only this, the deletion of the file will also be automatically handled when updating a model. By default, when a model is updated, the old file will be automatically deleted if a new file is being uploaded. If you don't want the old images to be deleted then you can chain `dontDeleteOldFileOnUpdate` method.

```
// app/Models/User.php

use Illuminate\Http\UploadedFile;

public function saveableFields(): array
{
    return [
        'image' => FileField::new()
            ->setDirectory('images')
            ->dontDeleteOldFileOnUpdate(),
    ];
}
```

Available Fields
----------------

[](#available-fields)

```
Asdh\SaveModel\Fields\StringField::class
Asdh\SaveModel\Fields\IntegerField::class
Asdh\SaveModel\Fields\DatetimeField::class
Asdh\SaveModel\Fields\DateField::class
Asdh\SaveModel\Fields\TimeField::class
Asdh\SaveModel\Fields\PasswordField::class
Asdh\SaveModel\Fields\FileField::class
Asdh\SaveModel\Fields\BooleanField::class
```

Other field will be added in the future and I am open to pull requests.

Creating your own model field class
-----------------------------------

[](#creating-your-own-model-field-class)

You can create your own field class as well. To create one, you need to run an artisan command

```
php artisan make:field BooleanField
```

This will create a `BooleanField` class inside `App\ModelFields` directory and it will look like this:

```
