0

I am having an issue regarding post route in laravel. Everytime i try to post data into my model, I get a 419 error i.e my session has been expired. What would be the solution to this problem?

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'body'  => 'required',
    ]);

    $post = new Post;
    $post->title = $request->input('title');
    $post->body = $request->input('body');
    $post->save();

    return redirect('/posts')->with('success', 'Post created');
}

Following is the blade code

{!! Form::open(['action' => 'postsController@store', 'method' => 'POST']) !!}

    <div class='form-group'>
        {{ Form::label('title','Title') }}
        {{ Form::text('title','',['class'=>'form-control','placeholder'=>'Title']) }}
    </div>

    <div class='form-group'>
        {{ Form::label('body','Body') }}
        {{ Form::textarea('body','',['id'=>'article-ckeditor','class'=>'form-control','placeholder'=>'Body Text']) }}
    </div>

    {{ Form::submit('Submit',['class'=>'btn btn-primary']) }}

{!! Form::close() !!}

1 Answer 1

6

Add a CSRF field to the form:

{!! csrf_field() !!}

VerifyCsrfToken middleware (which is defaultly included in Laravel app) requires that each POST request contains a pre-generated CSRF token. This increases security (see CSRF Wiki page). If you want to disable this, you can either delete/stop using the VerifyCsrfToken middleware, or you can list URIs that should be excluded from CSRF verification (see documentation).

Sign up to request clarification or add additional context in comments.

5 Comments

@NicoHaase Because Laravel defaultly needs every POST request to have this csrf-token, which increases security. The code responsible for this is in the VerifyCsrfToken middleware.
If this is an absolute need, it would be good if you'd add that to your answer
It should automatically do this, or at least it used to.
@aynber Maybe it used to, but I've been working with Laravel since 4.2, and I've always had to manually include the csrf token in POST forms.
@aynber no, Laravel doens't include it by default. It generates it but you must include it in the form adding a hidden CSRF token field, so that the CSRF protection middleware can validate the request. The other option is to disable the CSRF Verification from the desired endpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.