顯示具有 laravel 標籤的文章。 顯示所有文章
顯示具有 laravel 標籤的文章。 顯示所有文章

2016年12月30日 星期五

建置網路服務案例 - 以繪禮物為例

今天晚上受邀至朋友舉辦的 Meetup 分享。

分享我如何將一個現成的 business idea (繪禮物 http://www.giftpaint.com) 轉化為網路服務,並且建置出來。

由於此 Meetup 與 coding 有關,所以會簡單帶過 Laravel framework。
希望能讓一些想學程式或者有點子卻不知道如何開始的人有幫助。


2016年11月17日 星期四

Laravel 5.2 發送內部 Request 來呼叫現成 AJAX API

如果我在 Laravel Controller 內部,想要 call 另外一個現成的 AJAX 做事怎麼辦呢?
我們可以利用內部 Routing 機制,不用真的發 HTTP request,就可以達到類似的效果了。

以下這段程式情境如下:
  1. 我們的顯示購物車頁面,有一個參數是欲加入的商品代號。如果這個參數有值,會先將此商品加入購物車以後才出現商品清單畫面,使用者從這個畫面開始結帳流程。
  2. 在此之前,我們的使用者是利用一隻 AJAX API 來將商品加入購物車。
public function getCheckoutForm(Request $request) {
        $productId = $request->input('product_id', null);
        if(!empty($productId)) {
            // http://stackoverflow.com/questions/16597420/how-can-i-access-query-string-parameters-for-requests-ive-manually-dispatched-i
            $rr = Request::create(route('post.ajax.addcart'), 'POST', ['product_id' => $productId, '_token' => csrf_token()]);

            // Store the original input of the request and then replace the input with your request instances input.
            $originalInput = $request->input();
            $request->replace($rr->input());
            $response = Route::dispatch($rr);
            $request->replace($originalInput);
        }
        // getCheckoutForm() business logic
}

在這裡我們可以看到
  1. 我們先建立新的 Request 物件 $rr。
  2. 然後備份目前的 request input
  3. 將目前的 request input 置換成 $rr 的 input
  4. 利用 Route::dispatch() 產生 Request call
  5. 呼叫完畢以後再把目前 request input 換回來

參考