Reputation: 462
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.
Upvotes: 0
Views: 2460
Reputation: 2907
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>';
}
Upvotes: 1
Reputation: 33186
You have added the fields, but you need to concatenate the csrf_token()
value to your string. Right now, it will literaly print csrf_token
as value.
Try this:
$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>';
Also, the csrf_field()
function will echo an input field with the tokens value to the current request, csrf_token()
will display only the token value.
Upvotes: 1