Save Model is a Laravel package that allows you to save data in the database in a new way.

Overview

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 GitHub Tests Action Status GitHub Code Style Action Status Total Downloads


Installation

You can install the package via composer:

composer require asdh/save-model

You can publish the config file with:

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

// 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();
            }),
    ];
}

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

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

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:



namespace App\ModelFields;

use Asdh\SaveModel\Fields\Field;

class BooleanField extends Field
{
    public function execute(): mixed
    {
        // Perform your logic and return the value...

        // return strtoupper($this->value)
    }
}

It is not necessary that BooleanField class must be inside App\ModelFields directory. You can place it wherever you like.

You will have access to the data passed from the controller as $this->value. Then you can do whatever you want to do and return the value that you want to save in the database. In above case, we can do it like so:



namespace App\ModelFields;

use Asdh\SaveModel\Fields\Field;

class BooleanField extends Field
{
    public function execute(): mixed
    {
        return in_array($this->value, [1, '1', true, 'true', 'on', 'yes']);
    }
}

If the input is any one of these, then we will consider it to be true and for every one of these values, we will save true (which will be 1 when stored in database) to the database.

Then you can easily use your own field in the model's saveableFields method. You can now use this BooleanField along with other fields like this:

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;
use App\ModelFields\BooleanField;

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(),
            'is_admin' => Boolean::new(),
        ];
    }
}

Make sure you add the namespace correctly as shown above.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
A new way of Running Tinker. Simplify the Web Artisan's workflow.
A new way of Running Tinker. Simplify the Web Artisan's workflow.

Tinkerun A new way of Running Tinker. Simplify the Web Artisan's workflow. inspired by Tinkerwell Download links Github Releases 🗒 If you are using V

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.
A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

A Laravel package helps you add a complete real-time messaging system to your new / existing application with only one command.

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

This package helps you to add user based follow system to your model.

Laravel Follow User follow unfollow system for Laravel. Related projects: Like: overtrue/laravel-like Favorite: overtrue/laravel-favorite Subscribe: o

This package provides new helper functions that take care of handling all the translation hassle and do it for you.

Laravel Translate Message 🥳 This package provides new helper functions that take care of handling all the translation hassle and do it for you. Insta

An easy way to get vendor and package data from Packagist via API calls
An easy way to get vendor and package data from Packagist via API calls

Laravel Packagist Laravel Packagist (LaravelPackagist) is a package for Laravel 5 to interact with the packagist api quickly and easily. Table of cont

Convert remote api response data into laravel model
Convert remote api response data into laravel model

laravel remote model Create remote driver to convert remote api request into laravel model. 中文文档 日本語文書 overview Install the version between laravel5.5

LaravelFly is a safe solution to speeds up new or old Laravel 5.5+ projects, with preloading and coroutine, while without data pollution or memory leak

Would you like php 7.4 Preloading? Would you like php coroutine? Today you can use them with Laravel because of Swoole. With LaravalFly, Laravel will

Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

Owner
Laratips
Laratips is the place to learn about web development from basics to advanced.
Laratips
Validate your input data in a simple way, an easy way and right way. no framework required. For simple or large. project.

wepesi_validation this module will help to do your own input validation from http request POST or GET. INTEGRATION The integration is the simple thing

Boss 4 Dec 17, 2022
A laravel package to handle sanitize process of model data to create/update model records.

Laravel Model UUID A simple package to sanitize model data to create/update table records. Installation Require the package using composer: composer r

null 66 Sep 19, 2022
The query filter bundle allows you to filter data from QueryBuilder and the Database.

The query filter bundle allows you to filter data from QueryBuilder and the Database. you can filter multiple columns at the same time and also you can filter relation fields with two-level deep and without any join in your query builder.

Bugloos 15 Dec 29, 2022
A laravel package to generate model hashid based on model id column.

Laravel Model Hashid A package to generate model hash id from the model auto increment id for laravel models Installation Require the package using co

Touhidur Rahman 13 Jan 20, 2022
A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Touhidur Rahman 17 Jan 20, 2022
This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.

Laravel Verify New Email Laravel supports verifying email addresses out of the box. This package adds support for verifying new email addresses. When

Protone Media 300 Dec 30, 2022
A laravel package to handle model specific additional meta fields in an elegant way.

Laravel Meta Fields A php package for laravel framework to handle model meta data in a elegant way. Installation Require the package using composer: c

Touhidur Rahman 26 Apr 5, 2022
Laravel-model-mapper - Map your model attributes to class properties with ease.

Laravel Model-Property Mapper This package provides functionality to map your model attributes to local class properties with the same names. The pack

Michael Rubel 15 Oct 29, 2022
Foreman is a Laravel scaffolding application that automates common tasks you typically perform with each new Laravel app you create

Foreman is a Laravel scaffolding application that automates common tasks you typically perform with each new Laravel app you create. The directives you want Forman to perform are outlined in a JSON based template file.

Indatus 145 Apr 13, 2022
Easy way to upload Laravel model related files from the request.

Easy way to upload laravel model related file from the requset.

Emon Khan 5 Dec 15, 2022