B
B
belorusovbelorus2018-04-16 08:51:37
Laravel
belorusovbelorus, 2018-04-16 08:51:37

How to write ajax routes in Laravel?

I'm doing a course project in Laravel.

There are routes:

// Start page
Route::get('/', '[email protected]');
// Search
Route::post('/searchSimple', ['as' => 'searchSimple', 'uses' => '[email protected]']);

Searching from the start page calls an ajax request:

type: 'POST',
url: 'searchSimple',
data: {
'_token': "{{ csrf_token() }}",
'search': search
},


search is the input data.

The results are returned in json and loaded into the modal window. Everything works, but there is a catch - if you go to the /searchSimple route in the browser, then the no message error pops up. Question - how to write routes for ajax in Laravel? After all, I don’t need anything to open when I go to the browser along this route. I do not understand. I know it's a stupid question, but here it is. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
iljaGolubev, 2018-04-16
@belorusovbelorus

It can be so. Middleware - connect and specify for the necessary routes.

namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class AjaxOnly
{
public function handle($request, Closure $next)
    {
        if(!$request->ajax()){
            throw new BadRequestHttpException('This resource only accepts an ajax requests');
        }
        return $next($request);
    }
}

But it's better to make /searchSimple show the search form. And search to do through GET, by the way.

M
Matvey Pravosudov, 2018-04-16
@oxyberg

For example, you can throw a middleware on a group of routes for Ajax... . If not, redirect home.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question