Intercepting Data Before and After Saving in CRUDBooster

Intercepting Data Before and After Saving in CRUDBooster
By Ferry Oct 31, 2025 62 views
 

Hey everyone! If you've ever worked with admin panels, you know that sometimes you need to run custom logic right when a user saves a form. Maybe you need to generate a unique slug, send a notification, or log an action to an audit trail. Hacking the core logic is messy and a big no-no.

Luckily, CRUDBooster gives us a super clean way to hook into the form-saving process using simple event attributes. Today, we'll dive into two of the most useful ones: #[OnFormSaving] and #[OnFormSaved]. Let's get into it!

What You'll Need

Before we start, you just need one thing:

  • A CRUDBooster module that you've already created. We'll be working inside the Form Component file for that module (e.g., app/Cb/Modules/YourModule/Livewire/YourModuleForm.php).

That's it! No complex setup required.


Running Code Before Data Hits the Database with #[OnFormSaving]

The #[OnFormSaving] attribute is your go-to when you need to do something before the data is written to your database. This is the perfect place for last-minute data validation, modification, or preparation.

How to Use It

Inside your Form Component class, you simply create a public function and add the #[OnFormSaving] attribute right above it. CRUDBooster will automatically find it and run it at the right time.

PHP

use CrudBooster\Attributes\OnFormSaving;
// Make sure you are in your Form Component class, e.g., ProductsForm.php

class ProductsForm extends BaseFormComponent
{
    public function init() 
    {
        // Your form fields are defined here...
    }

    #[OnFormSaving]
    public function beforeSave($model, $data, $uuid = null)
    {
        // Your custom logic goes here!
        // This code will run right before the data is saved.
    }
}

CRUDBooster passes three arguments to your function:

  • $model: The model class for the module.

  • $data: An array containing all the data submitted from the form.

  • $uuid: The unique ID of the record (this will be null if you're creating a new record).

Use Case: Custom Validation

Imagine you want to prevent a user from creating a product if another product with a similar name already exists. This is a perfect job for #[OnFormSaving].

PHP

use App\Cb\Modules\Products\Models\Products;
use CrudBooster\Attributes\OnFormSaving;
use Illuminate\Support\Str;

//... inside your form component

#[OnFormSaving]
public function beforeSave($model, $data, $uuid = null)
{
    // Let's check for a similar product name
    $similarProduct = Products::where('name', 'like', $data['name'].'%')->first();

    // If we're creating a new product and a similar one exists...
    if (!$uuid && $similarProduct) {
        // Stop the process and throw an error!
        throw new \Exception("A product with a very similar name already exists. Please choose a different name.");
    }
}

With this simple function, the save operation will be halted if our condition is met, and the user will see an error message. Clean and effective!


Taking Action After a Successful Save with #[OnFormSaved]

Once your data is safely stored in the database, you might want to trigger a follow-up action. That's where #[OnFormSaved] comes in. It runs after the INSERT or UPDATE query has successfully completed.

How to Use It

Just like before, you define a public function in your Form Component and add the #[OnFormSaved] attribute.

PHP

use CrudBooster\Attributes\OnFormSaved;
// Make sure you are in your Form Component class

class ProductsForm extends BaseFormComponent
{
    public function init() 
    {
        // Your form fields are defined here...
    }

    #[OnFormSaved]
    public function afterSave($model, $data, $uuid = null)
    {
        // Your custom logic goes here!
        // This code will run right after the data has been successfully saved.
    }
}

The arguments are the same, giving you full context about the data that was just saved.

Use Case: Sending a Notification Email

A classic example is sending a notification when a new record is created. Let's say we want to email an admin every time a new product is added to the catalog.

PHP

use CrudBooster\Attributes\OnFormSaved;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

//... inside your form component

#[OnFormSaved]
public function afterSave($model, $data, $uuid = null)
{
    // Check if it's a new record. The $uuid is only available after saving a new entry.
    // If $data['id'] is present, it's an update, so we can also check that.
    $isCreating = empty($data['id']);

    if ($isCreating) {
        $productName = $data['name'];
        $adminEmail = 'admin@yourapp.com';
        
        // Send an email
        // Mail::to($adminEmail)->send(new NewProductNotification($productName));

        // Or just log a message for demonstration
        Log::info("A new product '{$productName}' has been added with UUID: {$uuid}");
    }
}

Now, every time a new product is created, your application can automatically fire off an email or log the event. Other great use cases include clearing a specific cache, updating a related model, or pushing data to an external API.

Wrap-Up

These two simple attributes, #[OnFormSaving] and #[OnFormSaved], give you incredible power to extend CRUDBooster's functionality. They allow you to add complex business logic directly into your modules in a way that is clean, maintainable, and upgrade-safe.