Mr.Singh
Mr.Singh

Reputation: 1781

Laravel: validate ajax request

In my laravel application, I am loading the forms via ajax request. I need to validate every method, such as create & edit, to be only the ajax request. But if they are called via get then they should be redirected with an error message.

I am using the following code. Its working fine but I have to write it on every method which I need to protect.

SomeController.php, AnotherController.php, YetAnotherController.php, ...:

public function create()
{
    if(!request()->ajax())
    {
        # setting error message
        session()->flash('warning', 'Invalid request method or method not allowed');

        # redirecting
        return redirect()->route("admin.dashboard");
    }

    ...
}

public function edit()
{
    if(!request()->ajax())
    {
        # setting error message
        session()->flash('warning', 'Invalid request method or method not allowed');

        # redirecting
        return redirect()->route("admin.dashboard");
    }

    ...
}

Is there a way to validate the specified methods for every controller in the application..?

Upvotes: 0

Views: 257

Answers (4)

Mr.Singh
Mr.Singh

Reputation: 1781

Thanks to @OmerYILMAZ and others who helped, here is my final code...

app\Http\Middleware\AllowedAjaxRequests.php:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Route;

class AllowedAjaxRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        # variables
        $ajaxMethods   = ['create', 'update'];
        $currentAction = Route::getCurrentRoute()->getActionMethod();

        # validating request method
        if (in_array($currentAction, $ajaxMethods) && !$request->ajax())
        {
            # setting error message
            session()->flash('warning', 'Invalid request method or method not allowed');

            # redirecting
            return redirect()->route("admin.dashboard");
        }

        return $next($request);
    }
}

app\Http\Kernel.php:

class Kernel extends HttpKernel
{
    ...

    protected $routeMiddleware = [
        ...

        'ajaxRequests' => \App\Http\Middleware\AllowedAjaxRequests::class,
    ];

    ...
}

routes\web.php:

Route::middleware(['ajaxRequests'])->group(function() {
    ...
});

Upvotes: 0

Omer YILMAZ
Omer YILMAZ

Reputation: 1263

In your Controller.php's __construct add this:

public function __construct ()
{
    $ajaxMethods = ['insert', 'update'];

    $currentActionMethod = Route::getCurrentRoute ()->getActionMethod ();

    if ( in_array ( $currentActionMethod, $ajaxMethods ) AND ! request ()->ajax () )
    {
        return redirect ()->back ()->with ( 'warning', 'Invalid request method or method not allowed' );
    }
}

Or Create a middleware

public function handle($request, Closure $next)
{

    $ajaxMethods = ['insert', 'update'];

    $currentActionMethod = Route::getCurrentRoute ()->getActionMethod ();

    if ( in_array ( $currentActionMethod, $ajaxMethods ) AND ! request ()->ajax () )
    {
        return redirect ()->back ()->with ( 'warning', 'Invalid request method or method not allowed' );
    }

    return $next($request);
}

Upvotes: 1

arya_la
arya_la

Reputation: 532

one way in to add it to your helper,so the only thing you should is first create a validation method in your helper.php, then defined it in your autoload section in your composer.json and finish. call your function anywhere you want. let me know if you want example or have question about it

Upvotes: 0

Nipuna Manoratne
Nipuna Manoratne

Reputation: 1

Try using a middleware, validate it and call the middleware in the constructor of the controller

Upvotes: 0

Related Questions