2014-04-09 5 views
0

쿠키와 Laravel을 함께 사용하는 것은 이번이 처음입니다. 간단한 값인 sectionID을 저장하고 사용자가 검색하여 마지막으로 방문한 섹션에서 작업을 계속할 수 있도록하려고합니다.Laravel 및 쿠키 이해하기

Route::get('cookieget', function() { 
    return Cookie::get('sectionID', 0); 
}); 

Route::post('cookieset', function() { 
    Cookie::make('sectionID', Input::get('sectionID'), 60*24); 
}); 

클라이언트 측이 꽤 복잡하지만, 이러한 관련 부분은 다음과 같습니다 : 더 저장 값이없는 경우에, 나는 0

서버 측 루트 반환 할

UserController.js을

function UserController(userID) { 
    var outer = this; 

    ... 

    this.setCookie = function(maxUserSectionID) { 

     $.ajax({ 
      type: 'POST', 
      url: "cookieset", 
      data: { 
       sectionID: maxUserSectionID 
      }, 
      success: function(data) { 
       console.log("Set max sectionID cookie to " + maxUserSectionID); 
      } 
     }); 
    } 

    this.getSectionIDFromCookie = function() { 
     $.ajax({ 
      type: 'GET', 
      url: "cookieget", 
      async: false, 
      success: sectionController.handleNewSection 
     }); 


    } 
} 

SectionController.js

function SectionController(editor, lessonNr) 
{ 

    // setup initial data 
    // the 0-based index of the current section 
    this.currentSection = null; 
    // the furthest the user has reached in this lesson 
    this.maxSection = 0; 
... 

    // methods 

    this.nextSection = function() { 

     if (outer.currentSection > outer.maxSection) { 
      outer.maxSection = outer.currentSection; 
      userController.setCookie(outer.lessonJSON['sections'][outer.maxSection]['sectionID']); 
     } 

    ... 
    }; 

    ... 

    this.checkCookie = function() { 
     userController.getSectionIDFromCookie(); 
    } 

    this.handleNewSection = function(newSectionID) { 
     alert(newSectionID); 
     outer.currentSection = parseInt(newSectionID); 
... 
    } 

    // called from outside as "constructor" 
    this.setup = function() { 
     ... 
    outer.checkCookie(); 
    } 

} 

우선, 내 주요 문제는 setCookie이 성공적으로 호출되었다고하더라도 쿠키가 항상 0을 반환한다는 것입니다.

둘째, 더 우아한 방법이 있는지 궁금합니다. 지금 서버가 너무 빨리 섹션을 이동하는 경우 많은 부하를 서버에 가하는 것으로 가정합니다.

+0

시도'위해서 var_dump (입력 : ('sectionID')를 얻을)은'cookieset' 노선에'? –

답변

1

제대로 쿠키를 설정 쿠키 응답을 반환해야합니다 :

Route::post('cookieset', function() { 
    $response = Response::make('Hello World'); 

    return $response->withCookie(Cookie::make('sectionID', Input::get('sectionID'), 60*24);); 
}); 
+0

고맙습니다. 작동하는 것 같습니다. 클라이언트의 구조는 어떻습니까? 일반적으로 쿠키를 사용하는 좋은 방법입니까? –

+0

아무 문제가 보이지 않지만 저는 자바 스크립트 전문가가 아닙니다. –

+0

나는이 질문에 답을 표시 할 것이다. 그러나, 나는 그 쿠키가 내가 찾던 것이 아니라는 것을 발견했다. –