How to do an Insert getting FORM data in Laravel 5.2?

4

I'm looking at the Laravel documentation on dbquery, in the insert case. I need to make the insert out of the resource method (manually.

Type:

DB::table('users')->insert(
    ['email' => '[email protected]', 'votes' => 0]
);

But I need to get the data of a form. How do I do this? I did not see it in the documentation.

    
asked by anonymous 12.01.2017 / 16:01

2 answers

3

Controller:

$model = new Model;
$model->nome = $request->get('nome'); // Vem do Form
$model->email = $request->get('email'); // Vem do Form
$model->telefone = $request->get('telefone'); // Vem do Form

$model->save();
    
12.01.2017 / 16:19
3

You need to point your form to the route where the destination is the function you will insert, for example;

Your form:

<form method="post" action="{{ route('cadastro/novo') }}">
...
</form>

Your Route:

Route::post('cadastro/novo', 'UsuariosController@create');

In the Controller UsuariosController you can use the User class to manipulate the DB data because every model is attached to a table in the database BY the plural, for example;

model user - > table users

model cat - > table cats

use App\User;

class UsuarioController extends Controller {

// A função Request tera todos os dados enviados via post.
public function create(Request $request) {

    // Pega os dados enviado atraves do POST exceto o input _token 
    // que é enviado por padrão atraves do form.
    $dados = $request->except('_token');

    // A inserção acontece aqui...
    User::create($dados);
}

To perform search in the database you can continue using the model you want, since it already has several methods to facilitate the manipulation.

$user = User::find(1); // Busca o usuario com o ID 1
$user = User::where('nome', 'oNome'); // Busca o usuario onde o campo "nome" seja "oNome".

In case of udpate you can do;

User::where('id', 999)->update(['sobrenome' => 'novoSobreNome']);
// Buscara e atualizara o usuário com ID 999 substituindo o campo sobrenome com "novoSobreNome"

OR

$user = User::where('id', 999);
$user->idade += 1;
$user->save();

You can refer to all available methods accessing the Eloquent page of laravel.

    
12.01.2017 / 16:11