Giter Club home page Giter Club logo

eloquent-nested-attributes's Introduction

eloquent-nested-attributes

Latest Version on Packagist Software License Build Status Total Downloads

Nested attributes allow you to save attributes on associated records through the parent. By default nested attribute updating is turned off and you can enable it using the $nested attribute. When you enable nested attributes an attribute writer is defined on the model.

Structure

If any of the following are applicable to your project, then the directory structure should follow industry best practises by being named the following.

src/
tests/
vendor/

Install

Via Composer

$ composer require mits87/eloquent-nested-attributes

Usage

namespace App;

use Eloquent\NestedAttributes\Model;

class Post extends Model
{
    protected $fillable = ['title'];
    
    protected $nested = ['option', 'comments'];

    public function option() {
        //it can be also morphOne
        return $this->hasOne('App\Option');
    }

    public function comments() {
        //it can be also morphMany
        return $this->hasMany('App\Comment');
    }
}

or

namespace App;

use Illuminate\Database\Eloquent\Model;
use Eloquent\NestedAttributes\Traits\HasNestedAttributesTrait;

class Post extends Model
{
    use HasNestedAttributesTrait;

    ...
}

usage:

\App\Post::create([
    'title' => 'Some text',

    'option' => [
        'info' => 'some info'
    ],

    'comments' => [
        [
            'text' => 'Comment 1'
        ], [
            'text' => 'Comment 2'
        ],
    ]
]);


\App\Post::findOrFail(1)->update([
    'title' => 'Better text',

    'option' => [
        'info' => 'better info'
    ],

    'comments' => [
        [
            'id' => 2,
            'text' => 'Comment 2'
        ],
    ]
]);

to delete nested row you should pass _destroy attribute:

\App\Post::findOrFail(1)->update([
    'title' => 'Better text',

    'option' => [
        'info' => 'better info'
    ],

    'comments' => [
        [
            'id' => 2,
            '_destroy' => true
        ],
    ]
]);

Change log

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

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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

eloquent-nested-attributes's People

Contributors

joaoroyosilva avatar kashif-umair avatar mits87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

eloquent-nested-attributes's Issues

Mass Assignment Exception thrown if $fillable array is empty

Expected behaviour

Given a model:

<?php

namespace App;

use App\TitleTranslation;
use Eloquent\NestedAttributes\Traits\HasNestedAttributesTrait;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasNestedAttributesTrait;

    protected $nested = [
        'titles'
    ];

    public function titles()
    {
        return $this->morphMany(TitleTranslation::class, 'translatable');
    }
}

And this payload:

{
	"titles": [
		{
			"text": "test title english",
			"language": "en"
		},
		{
			"text": "test title french",
			"language": "fr"
		}
	]
}

You would expect to be able to create a Task with:

    public function store(Request $request)
    {
        $task = Task::create($request->merge(json_decode($request->getContent(), true))->all());

        return TaskResource::make($task);
    }

And recieve a response like:

{
    "data": {
        "id": 20,
        "titles": [
            {
                "id": 11,
                "translatable_id": 20,
                "translatable_type": "App\\Task",
                "text": "test title english",
                "language": "en",
                "created_at": "2019-02-27 21:05:01",
                "updated_at": "2019-02-27 21:05:01"
            },
            {
                "id": 12,
                "translatable_id": 20,
                "translatable_type": "App\\Task",
                "text": "test title french",
                "language": "fr",
                "created_at": "2019-02-27 21:05:01",
                "updated_at": "2019-02-27 21:05:01"
            }
        ],
        "created_at": {
            "date": "2019-02-27 21:05:01.000000",
            "timezone_type": 3,
            "timezone": "UTC"
        }
    }
}

Actual result

Instead what you get is a MassAssignmentException as such:

Illuminate \ Database \ Eloquent \ MassAssignmentException
Add [titles] to fillable property to allow mass assignment on [App\Task].

I found the reason is because of how the fill() method on the Eloquent Model checks totallyGaurded().

The method looks like this:

    public function totallyGuarded()
    {
        return count($this->getFillable()) === 0 && $this->getGuarded() == ['*'];
    }

Which returns true if the $fillable array is emtpy and you haven't modified the default $gaurded. When totallyGaurded() returns true the fill() method throws a MassAssignmnetExeption.

The tests fail to capture this because the ModelEloquentStub has a value in the $fillable array.

The fix

The solution is to simply unset each attribute inside the fill() override when it is a nested attribute and after it has been saved to the $acceptedNestedAttributesFor array. This way, nested attributes never get passed to the parent fill() method.

I submitted a PR with the fix before I fully understood the bug: #3

Still have to update that PR with a test proving the bug.

Morphable relations

I wrote a similar piece of code for a proprietary project and discovered morphable relations should be taken into account as well. So hasOne can also be morphOne and hasMany can also be morphMany.

It might be useful to add those cases too.

update for Laravel 6

Really helpful package!
Too late to find this package..
Could you update this package for Laravel 6 ? Thanks😊

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.