User Registration in Laravel

Asked

Viewed 1,283 times

2

I’m starting with Laravel for a couple of weeks and automatically it’s raining with doubts.

I have a registration form with the following button below:

<button type="button" class="btn btn-primary" id="cadastrar-usuario">
<i class="fa fa-check"></i> Cadastrar Usuário
</button>

I have a Usuariocontroller.php that lists the Users, remembering that I am not using the table users of the same Language, I will use later.

I would like to call a Function from my controller.

My Controller is like this:

<?php namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;


class UsuarioController extends Controller {

    public function lista(){
        $usuarios = DB::select("select * from usuarios");

        return view('usuarios.listagem')->with('usuarios', $usuarios);
    }

}

?>

How could I call him using ajax?

2 answers

1

Just to complement the previous answer!
You can use the return method as follows.
Creating a user table template, using the Eloquent feature and then calling it in your Controller:

return response()->json(Usuarios::all());

Or returning your variable $usuarios thus:

return response()->json(['usuarios' => $usuarios]);

Either of these forms will return you a JSON object.

  • Don’t understand if it’s a question or an answer?

  • Just to complement the publication of the first reply, how it can perform the return in JSON

  • When it’s complimentary you can Edit your answer or by the Add-ons in the Comments... This will make your question/Answer clearer and readable.

1


First you need to create a route in the route file on app/Http/routes.php, add:

Route::get('listausuarios', 'UsuarioController@lista');

In your View Javascript, whereas you are using Jquery, add the click event to the button:

jQuery(document).ready(function ($) {

    $("#cadastrar-usuario").on('click', function() {

        jQuery.get("listausuarios", function(data){
            //Tratamendo dos dados recebidos em formado json
        });
});

I saw you return a view, instead of a JSON in your Controller. You’d have to change that too. But if you just want to click the button and change route, you can do it as follows in Javascript:

jQuery(document).ready(function ($) {

    $("#cadastrar-usuario").on('click', function() {
        window.location.href = 'listausuarios';
    });
});

Browser other questions tagged

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