micky
micky

Reputation: 317

Where should i place the route

I have this controller:

 public function watchlist(Request $request)
    {
        if($request->ajax())
        {
            $id=$request->id;
            if($id)
            {
                $add=new Watchlist();
                $add->product_id=$id;

                if(!Auth::check())
                {            
                    echo json_encode(FALSE);die;                        
                }

                $add->user_id=Auth::user()->id;      
                $add->save();        
                echo json_encode(TRUE);die;
            }

            echo json_encode(FALSE);die;
        }
    }

and the route is:

Route::post('/product/watchlist', 'ProductController@watchlist');

where should i place this route? If i place this route under auth and web middleware group i got

token mismatch exception.

Route::group(['middleware' => ['web']], function () {
    Route::get('/product/addform', 'ProductController@addform');    
    Route::post('/product/add', 'ProductController@add');

   Route::group(['middleware' => ['auth']], function () {
        Route::get('/','ProductController@index');  
        Route::get('/product','ProductController@index');               
        Route::post('/product/watchlist', 'ProductController@watchlist'); //here
    });
});

if i put it outside of web and auth middleware group

i couldnot get id of the user i need.

And if i put it under new auth middleware group outside web middleware group

 Route::group(['middleware' => ['auth']], function () {
                 Route::post('/product/watchlist', 'ProductController@watchlist');
    )};    

i got

Unauthorized

Upvotes: 1

Views: 61

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

As you're making use of user's session in your controller, for sure your route should be put under the web middleware so that user session is handled correctly.

However, in order for it to work, you'll need to make sure that you pass the XSRF token along with your AJAX request. You'll find the token in XSRF-TOKEN cookie that Laravel creates. You'll need to pass it in X-XSRF-TOKEN header of your request.

Regarding auth middleware, you should add that to the request only for requests that require user to be authenticated.

Upvotes: 1

Related Questions