2017-03-09 9 views
0

フレンドリクエストを受け入れるための小さなヘルパー機能を作成しました。この関数は、PHPファイル内にある(当然)と次のようになります。PHPフォーム内のLaravel csrfトークン

(関連部分のみ)

foreach($friendrequests as $request){ 
    $username = DB::table('users')->where('id', $request->sender_id)->value('name'); 
    $notify .= '<li>'; 
    $notify .= '<strong><a href="/profile/'.$username.'">'.$username.'</a></strong><br>möchte dein Freund sein'; 
    $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Akzeptieren</button></form>'; 
    $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="csrf_field();"><button type="submit">Ablehnen</button></form>'; 
    $notify .= '</li>'; 
} 

私はそれが一種の厄介だ知っています。私はLaravelにとってかなり新しいです。

いずれにしても、2つの形式があります。受け入れるものと要求を拒否するもの。今私が苦労しているのはcsrfトークンです。

これをPHPヘルパーファイルに実装するにはどうすればよいですか?私はブレードテンプレートでそれらを使用する方法を知っていますが、ヘルパー機能内で動作させることはできません。

答えて

1

次のようにコードに_token隠し要素を追加してみてください。 csrf_token()helper functionを使用して、フォーム内にフォームトークンを追加することもできます。

foreach($friendrequests as $request){ 
     $username = DB::table('users')->where('id', $request->sender_id)->value('name'); 
     $notify .= '<li>'; 
     $notify .= '<strong><a href="/profile/'.$username.'">'.$username.'</a></strong><br>möchte dein Freund sein'; 
     $notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Akzeptieren</button></form>'; 
     $notify .= '<form action="/friend/request/deny/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="'.Session::token().'"><button type="submit">Ablehnen</button></form>'; 
     $notify .= '</li>'; 
    } 
1

フィールドを追加しましたが、csrf_token()の値を文字列に連結する必要があります。今は文字通りcsrf_tokenを値として印刷します。

はこれを試してみてください。また、

$notify .= '<form action="/friend/request/accept/'.$request->sender_id.'" method="post"><input type="hidden" name="_token" value="' . csrf_token() . '"><button type="submit">Akzeptieren</button></form>'; 

は、csrf_field()関数は、現在の要求にトークン値を入力フィールドをエコーし​​ます、csrf_token()はトークン値を表示します。

関連する問題