PHP code example of denizgolbas / eloquent-save-together

1. Go to this page and download the library: Download denizgolbas/eloquent-save-together library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

denizgolbas / eloquent-save-together example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Denizgolbas\EloquentSaveTogether\Eloquent\EloquentSaveTogether;

class Product extends Model
{
    use EloquentSaveTogether;

    protected $fillable = [
        'name',
        'description',
        'sku',
        'base_price'
    ];

    /**
     * Define which relationships should be saved together
     *
     * Format:
     * - 'relationName' => false  : Save/update only, don't delete missing records
     * - 'relationName' => true   : Save/update AND delete records not in request
     */
    protected array $together = [
        'prices' => true,           // Delete prices not in request
        'additionalTaxes' => true,  // Delete taxes not in request
        'units' => false,           // Only save/update, don't delete
        'categories' => false,      // Only save/update, don't delete
    ];

    // Define your relationships
    public function prices()
    {
        return $this->hasMany(ProductPrice::class);
    }

    public function additionalTaxes()
    {
        return $this->belongsToMany(Tax::class, 'product_taxes');
    }

    public function units()
    {
        return $this->hasMany(ProductUnit::class);
    }

    public function categories()
    {
        return $this->belongsToMany(Category::class);
    }
}



namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ' 'nullable|exists:product_prices,id',
            'prices.*.currency' => '.*.id',

            'units' => 'array',
            'units.*.id' => 'nullable|exists:product_units,id',
            'units.*.name' => 'lTogether($data)
                ->saveTogether();

        return response()->json($product->load(['prices', 'additionalTaxes', 'units']));
    }
}

protected array $together = [
    'prices' => true,        // Will DELETE prices not in the request
    'categories' => false,   // Will KEEP existing categories not in the request
];

// Database has: Price IDs [1, 2, 3]
// Request has: Price IDs [2, 4] and one new price

'prices' => true  // After save: Database will have [2, 4, 5]
                  // ID 1 and 3 are DELETED

// Database has: Category IDs [1, 2, 3]
// Request has: Category IDs [2, 4]

'categories' => false  // After save: Database will have [1, 2, 3, 4]
                      // ID 1 and 3 are KEPT

// Order model
class Order extends Model
{
    use EloquentSaveTogether;

    protected array $together = [
        'items' => true,
        'customer' => false,
    ];
}

// OrderItem model
class OrderItem extends Model
{
    use EloquentSaveTogether;

    protected array $together = [
        'discounts' => true,
        'taxes' => false,
    ];
}

// Usage - saves Order -> OrderItems -> Discounts/Taxes
$order = new Order();
$order->fillTogether($data)->saveTogether();

// config/eloquent-save-together.php
return [
    'relation_mappings' => [
        'App\Relations\CustomHasMany' => \Illuminate\Database\Eloquent\Relations\HasMany::class,
        'App\Relations\SpecialBelongsTo' => \Illuminate\Database\Eloquent\Relations\BelongsTo::class,
    ],
];

$product = new Product();
$fillableStructure = $product->getRelatedWithSubRelations();

// Returns:
// [
//     'name',
//     'description',
//     'sku',
//     'base_price',
//     'prices' => ['currency', 'amount'],
//     'units' => ['name', 'conversion_rate']
// ]

   // Model relationship: additionalTaxes()
   // Request key: additional_taxes
   
bash
php artisan vendor:publish --tag="eloquent-save-together-config"