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',
]);
}
謝謝,我以前沒有使用過特質。第一個問題是你能告訴我一個模型的例子。其次是我正在實施這個事實,所以我需要更新一堆我的控制器。有沒有辦法只是編碼和解碼的ID,所以我不會改變我的控制器使用'Model :: hashId()'? – Derek
最後得到它的工作,這篇文章幫助:https://laracasts.com/discuss/channels/laravel/how-to-make-a-trait-in-laravel-53 – Derek
@Derek我已經更新了我的答案在模型上使用特徵的例子 – fubar