php - unable to post data through button

I am trying to post data to the database via hidden field through a press of a button But the error that I am facing is 419 Page Expired
Here's My View:-
<div>
<h1> All Posts </h1>
@if(count($user) > 0)
@foreach($user as $post)
<form action="/f" method="POST">
<input type="hidden" id="friends" name="friends" value="{{$post->id}}" />
<button type="submit" class="btn btn-primary">
{{ __('chat') }}
</button>
</form>
<div class="well">
<a href="/profile/1"<button class="button btn-success">chat</button>></a>
<h3>{{$post->title}}</h3>
<h4>{{$post->body}}</h4>
<small>written on {{$post->created_at}}</small>
</div>
@endforeach
@else
<p>No Forms Found</p>
@endif
</div>
Here's My Route:-
Route::post('/f', 'FriendsController@store');
Here's My Controller:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FriendsController extends Controller
{
public function store(Request $request)
{ dd($request->all());
post::create([
'friends' => $request->friends,
]);
return redirect('/profile/' . auth()->user()->id);
}
}
I might have done mistake in my store method please do check and let me know whats wrong with it I'm just a beginner -ThankYou
Answer
Solution:
Error 419 means Page expired and in laravel, it comes from not having or having invalid CSRF token when making non-GET requests. You need to add a CRSF token to your form e.g by adding @csrf just after the form declaration:
<form action="/f" method="POST">
@csrf
<input type="hidden" id="friends" name="friends" value="{{$post->id}}" />
OR this way:
<form action="/f" method="POST">
{{csrf_field()}}
<input type="hidden" id="friends" name="friends" value="{{$post->id}}" />
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: attempt to read property "id" on null
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.