1

I have a web app that runs on Laravel 5.5 and I need to create a shopping cart using ajax exclusively (I have reasons).

When the user is logged in, all runs smoothly. When the user is not logged in I get a empty response.

Routes:

Route::post('/shop/add2', 'ShopController@addToCart')->name('add2cart');

ShopController looks something like:

<?php 

    class ShopController extends Controller
    {

      public static function addToCart(){

       $message = "Some message";

       return response()->json(["message"=>$message]);
      }
    }
?>

Jquery is :

var token  = $('[name="_token"]').val();
var var1  = $(this).data('itemcom');
var var2_  = $(this).data('itemvalue');
$.ajax({
      url: '/shop/add2',
      type: 'POST',
      data: {_token: token, identX:var2_, identY:var1 },
      dataType: 'JSON',
      success: function(response) {
        console.log(JSON.stringify(response));
      },
      error  : function(errors){
        console.log(JSON.stringi(errors));
      }
});

I tried everything I could and I get a 419 status code. I know, right?

2 Answers 2

1

If you don't mind that this function will be accessible to everyone, you can add a exception to the middleware in the constructor of the Controller:

public function __construct()
{
    $this->middleware('auth', ['except' => ['addToCart']]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the snippet. For some reason that did not work for me, some more digging brought to me to laravel-news.com/excluding-routes-from-the-csrf-middleware and that worked though it requires me to edit the App\Http\MIdleware\VerifyCsrToken.php file grrrrr
0

Hmm, I have a strong devaju with code 419... and not a good one. I had to debug like half a day because a missing Csrf token in a route for facebook's webhook. Maybe this is similar in your case?

class VerifyCsrfToken extends Middleware
{
    const FACEBOOK_ROUTE = 'facebook_hook';

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        self::FACEBOOK_ROUTE,
        self::FACEBOOK_ROUTE . '/*',
        'upload',
        'upload/*',
    ];

The same goes for my upload, which is done by a third party ajax plugin as well.

Cheers

1 Comment

That's what I found too. I had answered in the comments below. laravel-news.com/excluding-routes-from-the-csrf-middleware

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.