User Registration in Laravel

2

I'm starting with laravel about 2 weeks ago and it's automatically 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 UserController.php that lists the Users, remembering that I am not using the same users table of laravel, I will use it later.

I would like to call a function from my controller.

My Controller looks 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 it using ajax?

    
asked by anonymous 26.08.2016 / 16:49

2 answers

1


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

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

In Javascript of your View, considering that 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 that you return a view , instead of a JSON on your Controller. I would have to change that too. But if you just want to get the button click and change the route, you can do the following in Javascript:

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

    $("#cadastrar-usuario").on('click', function() {
        window.location.href = 'listausuarios';
    });
});
    
26.08.2016 / 17:45
1

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

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

Or by returning your $usuarios variable like this:

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

Any of these forms will return you a JSON object.

    
31.10.2018 / 17:37