2017-02-19 9 views
0

我使用hashid來散列url中的id參數。我有它在我的模型中設置自動散列id。這工作正常。我的問題是在中間件中解碼哈希返回null。我不確定這是我的中間件還是哈希的問題。L5在中間件中使用Hashid返回null

型號:

public function getIdAttribute($value) 
    { 
     $hashids = new \Hashids\Hashids(env('APP_KEY'),10); 
     return $hashids->encode($value); 
    } 

中間件:

<?php 

namespace App\Http\Middleware; 

use Closure; 

class HashIdsDecode 
{ 
    /** 
    * Handle an incoming request. 
    * 
    * @param \Illuminate\Http\Request $request 
    * @param \Closure $next 
    * @return mixed 
    */ 
    public function handle($request, Closure $next) 
    { 
     dd($request->id); //Returns null on show method - example localhost:8000/invoices/afewRfshTl 
     if($request->has('id')) 
     { 
      $hashids = new \Hashids\Hashids(env('APP_KEY'),10); 
      dd($hashids->decode($request->input('id'))); 
     } 

     return $next($request); 
    } 
} 

路線:

Route::resource('invoices','InvoiceController'); 

控制器:

public function show($id) 
    { 
     $invoice = Invoice::find($id); 
     return view('invoices.show', [ 
      'invoice' => $invoice, 
      'page_title' => ' Invoices', 
      'page_description' => 'View Invoice', 
     ]); 
    } 

注:如果我繞過中間件和在我的控制器這樣它直接做,但它需要我一遍又一遍,也許不是最好的方式重複自己做到這一點。

public function show($id) 
    { 
     $hashids = new \Hashids\Hashids(env('APP_KEY'),10); 
     $invoiceId = $hashids->decode($id)[0]; 
     $invoice = Invoice::find($invoiceId); 

     return view('invoices.show', [ 
      'invoice' => $invoice, 
      'page_title' => ' Invoices', 
      'page_description' => 'View Invoice', 
     ]); 
    } 

回答

0

就個人而言,我會更傾向於寫一個模型特質。然後,您可以僅使用所需模型的特徵,而不是假設請求中的每個ID參數都是哈希ID。

E.g.

namespace App\Models\Traits; 

use Hashids\Hashids; 
use Illuminate\Database\Eloquent\Builder; 

trait HashedId 
{ 
    public function scopeHashId(Builder $query, $id) 
    { 
     $hashIds = new Hashids(env('APP_KEY'), 10); 
     $id = $hashIds->decode($id)[0]; 

     return $query->where('id', $id); 
    } 
} 

然後使用它,你會用性狀上的發票模型(編輯):

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Invoice extends Model 
{ 
    use \App\Models\Traits\HashedId; 

    // ... 
} 

而在你的控制器執行以下查詢:

public function show($id) 
{ 
    $invoice = Invoice::hashId($id)->firstOrFail(); 

    return view('invoices.show', [ 
     'invoice' => $invoice, 
     'page_title' => ' Invoices', 
     'page_description' => 'View Invoice', 
    ]); 
} 
+0

謝謝,我以前沒有使用過特質。第一個問題是你能告訴我一個模型的例子。其次是我正在實施這個事實,所以我需要更新一堆我的控制器。有沒有辦法只是編碼和解碼的ID,所以我不會改變我的控制器使用'Model :: hashId()'? – Derek

+0

最後得到它的工作,這篇文章幫助:https://laracasts.com/discuss/channels/laravel/how-to-make-a-trait-in-laravel-53 – Derek

+0

@Derek我已經更新了我的答案在模型上使用特徵的例子 – fubar

相關問題