The first example of code, creates an instance of the class and takes the data passed and writes
//instancia uma classe Produto
//método atribui os valores configurados no fillable
//grava um novo registro na sua tabela e desenvolve uma instância desse registro
Product::create($request->all());
the other way serves to assign new values to non-existent or even existing data, ie, the second code can be used to save a new record or even change data of a record that already exists, calling finally the method save()
, example
$product = new Product();
$product->fill($request->all());
$product->save();
or
// buscando registro de número 1
$product = Produto::find(1)
// verificando se encontrou o produto
if ($produto)
{
//atribuindo novos valores ou apenas alguns valores
$product->fill($request->all());
}
// salvando os dados passados
$product->save();
note, that the method fill
only accepts the values set in fillable
, but, not required to pass all values and only past values will be changed or entered and also the values passed by this method does not guarantee that the data will be saved, because finally should call the method save()
.
In the same line as create
which already makes at once the creation of a new record, has the method update
which has the purpose of assigning the values and immediately after saving the changes, example:
// buscando registro de número 1
$product = Produto::find(1)
// verificando se encontrou o produto
if ($produto)
{
//atribuindo novos valores ou apenas alguns valores
// e salvando as alterações (sem precisa chamar método save())
$product->update($request->all());
}
References:
-1 Wrong. Both don’t do the same thing. The
fill
only fills the attributes in the model. Ocreate
creates the data. Basically, thecreate
uses thefill
internally and then callssave
. If you use thefill
withoutsave
, records in the database are not affected.– Wallace Maxters
Thank you, @Wallacemaxters
– Wictor Chaves