vendredi 9 novembre 2018

Is possible integrate trigger and validator in Laravel?

I am have a trigger.

CREATE OR REPLACE FUNCTION asset_constraint() RETURNS trigger AS $$

DECLARE
    max_assets INTEGER := 2;
    assets_count INTEGER := 0;
    must_check BOOLEAN := false;

BEGIN
    IF TG_OP = 'INSERT' THEN
        must_check := true;
    END IF;

    IF TG_OP = 'UPDATE' THEN
        IF (NEW.name != OLD.name) THEN
            must_check := true;
        END IF;
    END IF;

    IF must_check THEN
        -- prevent concurrent inserts from multiple transactions
        LOCK TABLE assets IN EXCLUSIVE MODE;

        SELECT INTO assets_count COUNT(*) 
        FROM assets; 
        --WHERE name = NEW.name;

        IF assets_count >= max_assets THEN
            RAISE EXCEPTION 'no puede añadir mas de % assets.', max_assets;
        END IF;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER asset_constraint 
    BEFORE INSERT OR UPDATE ON assets
    FOR EACH ROW EXECUTE PROCEDURE asset_constraint();

Database exception

The trigger works correctly, if it counts more than 2 records, then it sends an exception.

Now, I don't know if we can do this directly with a validator in laravel, without the trigger. I need to use the javascript "toast" functionality for the message, not the exception as shown in the orange picture.

User notifications work very well, when I do CRUD, I use ajax, requests and toast.

If the exception occurs, then customize the message in a request file for example... and show it as a "toast" message, on the right.

I really don't know how to do it, if to leave the trigger and make a validator that catches it, or makes a custom validator without the trigger.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire