如何修复'Illuminate \ Database \ Eloquent \ MassAssignmentException'上的_token错误

时间:2018-12-27 07:04:30

标签: php laravel

当尝试添加新类别来存储数据时遇到了此错误,但是它看到了_token错误?

CategoriesController.php

public function store(Request $request)
{
    Category::create($request->all());
    return back();
}

index.blade.php

<a class="btn btn-primary pull-right navbar-right" data-toggle="modal" href="#category">Add Category</a>
<div class="modal fade" id="category">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Add New</h4>
            </div>
            {!! Form::open(['route' => 'category.store', 'method' => 'post']) !!}
            <div class="modal-body">
                <div class="form-group">
                    {{ Form::label('name', 'Title') }}
                    {{ Form::text('name', null, array('class' => 'form-control')) }}

                </div>


            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
            </div>
            {!! Form::close() !!}
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

enter image description here

3 个答案:

答案 0 :(得分:1)

添加

protected $fillable = ['name'];

在您的Category班级下。

并使用

Category::create($request->only(['name']));

而不是$request->all(),它试图与categories._token一起组合写入您的Category模型中的create()列。

答案 1 :(得分:0)

您应该尝试以下操作:

<a class="btn btn-primary pull-right navbar-right" data-toggle="modal" href="#category">Add Category</a>
<div class="modal fade" id="category">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Add New</h4>
            </div>
            {!! Form::open(['route' => 'category.store', 'method' => 'post']) !!}

            {!! csrf_field() !!}

            <div class="modal-body">
                <div class="form-group">
                    {{ Form::label('name', 'Title') }}
                    {{ Form::text('name', null, array('class' => 'form-control')) }}

                </div>


            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-primary">Save changes</button>
            </div>
            {!! Form::close() !!}
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

答案 2 :(得分:0)

您还可以添加

protected $guarded = [];

添加到模型,然后可以使用质量分配。