php – Ajax requests in Laravel


This is the sample code of a controller and the normal (not AJAX) handling of a Request.

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 for AJAX requests in store() function as well?

If I create another storeAjax() function, I can include it in routes.php (with a new route assigned) and it works, but not good practice as I have 2 routes and it must be the same for both requests.


Maybe this can help you:

if($request->ajax()){ }//procesa la peticion ajax 
else{return $view;} //retornas por ejemplo,una vista

As for the Routes.php , there is no need to modify, what you do in your JS is a GET type request:

$.ajax(type: 'GET', ...)

And you process the request, I hope it helps you.

Scroll to Top