What is the correct way to pass the view data to the model?

Asked

Viewed 293 times

1

Using Laravel, what is the best way to pass data from view to model? For example, form data and etc...

A while ago, I used Codeigniter and sent the data by ajax. In the case of Laravel, it would be the same thing, or has some better and more appropriate form?

1 answer

5


Generally, you can do the common flow of a framework

  • The view form is submitted, the data is processed by the controller and then passed to create a model.

A basic example of this can be seen like this:

View

{{  Form::open(['id' => 'meu-formulario']) }}
{{  Form::text('nome_produto') }}
{{  Form::submit('Enviar') }}
{{  Form::close() }}

Controller

public function postCadastrarProduto() 
{
   $input = Input::only('nome_produto');

   Produto::create($input);
}

Model

class Produto extends Eloquent
{
     protected $table = 'produtos';
     protected $fillable = ['nome_produto'];

}

If you want to make ajax requests, you can do so:

View

The same as before

Javascript

$.ajax({
    url: '/produtos/ajax-cadastrar-produto',
    type: 'POST',
    data: {nome_produto: $('#nome-produto').val()},
    success: function (response) {
        if (response.error) {
           return alert(response.error);
        }

        return alert('deu tudo certo');
    }       
});

controller

// Se der erro, retornará um json com o índice error com alguma mensagem

public function postAjaxCadastrarProduto() 
{
   $input = Input::only('nome_produto');

   Produto::create($input);

   return Response::json(['error' => false]);
}
  • That way the data would be sent without doing the reflesh on the page?

  • If you want to do with ajax, it’s also possible. It’s quite simple.

  • I usually use redirect, because in Windows it is possible to create flash in session easily. This makes my service easier ;)

  • Oh yes, very interesting, I didn’t know that Form::

  • @Silvioandorinha take into account that the Form is no longer standard in Laravel and can only be installed part.

  • 1

    Our man, very show! great answer, Thank you!

Show 1 more comment

Browser other questions tagged

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