Search code examples
phpcsrflaravel-5.4

Laravel csrf token within PHP form


I created a little helper function for accepting friend requests. This function lies within a PHP file (obviously) and looks like this:

(Only the relevant part)

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>';
}

I know it's kind of messy. I'm fairly new to Laravel.

Anyway, there are two forms. One for accepting and one for denying the request. Now the thing I'm struggling with is the csrf token.

How do I implement this within the PHP helper file? I know how to use them in the blade templates, but I can't seem to make it work within the helper function.


Solution

  • Try to add _token hidden element to your code as below. You can also use csrf_token() helper function to add the form token inside forms.

    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>';
        }