mysqllaravellaravel-backpackgenerated-columns

How to handle generated column in database table with Laravel Backpack?


I have a table in a MySQL database that contains a virtual generated column. It is defined in the appropriate migration using ->virtualAs().

I've tweaked the Create and Update operations of the default CRUD controller that Backpack generated for me -- I've made the generated column read-only:

->attributes(['readonly'=>'readonly'])  // virtual generated column in the DB

That works great to keep the user from trying to change the value of the generated column when they're creating or updating an entry.

But it creates a problem when trying to save an entry you've just created. The SQL Insert statement crashes because the generated column is included in the Insert statement, vis:

Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 3105 

The value specified for generated column 'type_subscr' in table 'subscriptions' is not allowed. 

(SQL: insert into `subscriptions` (`supporter_id_from`, `supporter_id_to`, `transaction_id`, `type_subscr`, 
`date_start`, `date_end`, `notes`, `updated_at`, `created_at`) values (305, 2218, 14091, ?, 
2023-03-15 00:00:00, 2024-03-14 00:00:00, TEST DATA ONLY, 2023-03-15 18:33:36, 2023-03-15 18:33:36))

I think I need to tell the Create operation of the Backpack controller not to include type_subscr in the Insert statement at all. Is that the correct approach? How would I do that?

Or is there something I need to do in my Laravel model and/or migration that would solve the problem at that level, without having to tweak my Backpack controller?


Solution

  • Instead of readonly, you should use disabled:

    ->attributes(['disabled'=>'disabled'])  // virtual generated column in the DB
    

    The difference between readonly and disabled in HTML inputs (and Backpack too, by extension):