Skip to content
Advertisement

Adding custom method to Laravel model causes create() to ignore attributes

In Laravel 8, I have already had a working DocumentPdf resource – at least I was able to create the object using DocumentPdf::create($attributes).

Now I want to create a custom method in the model, a one that will fill the document with $data and send it to browser. While it works for existing documents, adding the method broke create() in a way that when I send a filled form, I receive a IlluminateDatabaseQueryException:

SQLSTATE[HY000]: General error: 1364 Field ‘filename’ doesn’t have a default value (SQL: insert into document_pdfs (updated_at, created_at) values (2020-10-22 02:42:26, 2020-10-22 02:42:26))

It’s not a first custom method in the model, but the only breaking one – commenting out the method makes create() work again, but then I lose an ability to fill the document.

app/DocumentPdf.php:

JavaScript

app/Http/Controllers/DocumentPdfController.php:

JavaScript

How could I define such method not to break existing functionality? I’d like to have it in a model, since in the future I plan to handle other types of documents, e. g. DocumentXls, and have a parent abstract class Document that’d be handled by DocumentController.

Advertisement

Answer

fill is a Model method that fills the attributes of the Model. You should not override this; change your method name to something else.

IlluminateDatabaseEloquentBuilder@create creates a new instance of the Model with the data passed, which will call fill to fill the attributes for the Model.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement