Code reduced to Insert

Asked

Viewed 34 times

1

Say you have the following fields in the users table:

ID,NOME,USUARIO,LOGIN and SENHA

For me to enter a record in the table I do the following

$usuario = new Usuario();
$usuario->nome = 'Carlos Bruno';
$usuario->login = 'cbcarlos';
$usuario->senha = '123456';
$usuario->save();

There is a smaller code for me to do this insert, because if it were many fields?

Example:

$usuario = new Usuario( AllInput() )
$usuario->save()

Like if I wanted to pick from an array

Array(
 'Carlos Bruno',
 'cbcarlos',
 '123456' 
);

And insert in the base, would have as?

1 answer

2


Yes, there is a way to pass one array associative in the as an example:

$newarray = array(
 'nome' => 'Carlos Bruno',
 'login' => 'cbcarlos',
 'senha' => '123456' 
);

the array only one dimension will not work because, internally, the value is passed by the name of the key configured in the fillable, example:

class Usuario extends Eloquent 
{
    protected $fillable = array('nome', 'login', 'senha');
}

and to save can be done in two ways:

$usuario = new Usuario($newarray);
$usuario->save();

or

$usuario = Usuario::create($newarray);

If the values are coming from input and a request post, for example this works smoothly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.