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.
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/
Via Composer
$ composer require mits87/eloquent-nested-attributes
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
],
]
]);
Please see CHANGELOG for more information on what has changed recently.
$ composer test
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email mits87@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.