This is the example code of a controller and the normal handling (not AJAX) of a Request or request.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
class UserController extends Controller
{
/**
* Store a new user.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$name = $request->input('name');
//
}
}
What should I do to make it work also for AJAX requests in the function store()
?
If I create another function storeAjax()
, I can include it in routes.php (with a new route assigned) and it works, but it's not a good practice, since I have 2 routes and it must be the same for both requests.
Maybe this can help you:
As for the
Routes.php
, there is no need to modify, what you do in your JS is a request of typeGET
:And you process the request, I hope it helps you.
Use the following example to create a more powerful controller function.
-
AJAX request example:
Create a route that points to the Store method of your controller, which will serve both for requests from a form and for AJAX requests:
There is no need to implement another method.
If it doesn't work for you, it may be because Laravel 5 includes a CSRF token validation, for security reasons, in all POST, PUT and DELETE requests. You must include this token in the request.
You can see different methods to include this token in the official documentation: http://laravel.com/docs/5.1/routing#csrf-protection
you can try with this