【问题标题】:Laravel Controller/Ajax not saving in my databaseLaravel 控制器/Ajax 未保存在我的数据库中
【发布时间】:2021-09-02 01:51:32
【问题描述】:

我的类别中的save(); 似乎无法按以下预期运行。我将首先显示必要的代码:

我的表名是 hms_bbr_category,它也是本地连接到我的 .env 的:

DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=jhs
DB_USERNAME=postgres
DB_PASSWORD=pa55wor0

我的模型:HmsBbrCategory

类 HmsBbrCategory 扩展模型

{
    protected $table = 'hms_bbr_category';
    protected $fillable = [
        "category_name", "category_description"
    ];
}

我的控制器:BBRCategoryConfigurationController

class BBRCategoryConfigurationController extends Controller
{
    public function index(){
        return view('frontend.bbr-settings.bbr-category-configuration');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category_name'=>'required|max:191',
            'category_description'=>'required|max:191',
        ]);
        if($validator->fails())
        {
            return response()->json([
                'status'=>400,
                'errors'=>$validator->messages(),
            ]);
        }
        else {
            $category = new HmsBbrCategory;
            $category->category_name = $request->input('category_name');
            $category->category_description = $request->input('category_description');
            $category->save();
            return response()->json([
                'status'=>200,
                'message'=>'Category Added!',
               
            ]);
        }
        
    }

ajax 和 modal 字段

<div class="form-group">
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name">
</div> 
<div class="form-group">
<textarea class="form-control w-100 category_description" placeholder="Category Description" cols="50" rows="10"></textarea>
</div>

<script>
    $(document).ready(function (){
        $(document).on('click', '.add_category', function(e){
            e.preventDefault();
            var category_data = {
                'category_name': $('.category_name').val(),
                'category_description': $('.category_description').val(),
            }
            
            //token taken from laravel documentation
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            console.log(category_data);
            $.ajax({
                type: "POST",
                url: "/clinical/bbr-category-configuration",
                data: "category_data",
                dataType: "json",
                success: function (response){
                    // console.log(response);
                if(response.status == 400)
                    {
                    $('#saveform_errList').html("");
                    $('#saveform_errList').addClass('alert alert-danger');
                    $.each(response.errors, function (key, err_values) {
                        $('#saveform_errList').append('<li>'+err_values+'</li>');
                    });
                    }
                else 
                    {
                     $('#saveform_errList').html("");
                     $('#success_message').addClass('alert alert-success');
                     $('#success_message').text(response.message);
                     $.('#createCategory').modal('hide');
                     $.('#createCategory').find('input').val("");
                     console.log(category_data);
                    }
                }
            });
        });
    });
</script>

我在 web.php 的路线

Route::get('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'index']);
Route::post('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'store']);

注意事项:

我的预感是我的存储功能在$category = new HmsBbrCategory; 上没有正确连接但是我检查了我的表名和所采用的字段是否相同,如$category-&gt;category_name = $request-&gt;input('category_name'); 所示

我还通过简单地添加 console.log(response) 在 ajax 中对值进行了测试,如屏幕截图所示,我无法通过验证器到达 save()。我不知道怎么做,但应该不会有错误,因为我的文本字段已填满。

如果需要,我可以详细说明,我在问我可以更改什么来修复我的验证/保存。感谢您的帮助。

【问题讨论】:

  • 您应该已经阅读了验证器错误消息并使用 JS 中的 console.log() 和控制器中的 dd() 检查了您的数据。完整问题的道具

标签: ajax laravel forms controller save


【解决方案1】:

如错误所示,验证失败(我猜是空值)并返回您编写的代码(400)。

我猜这是因为您使用的是字符串而不是属性data: "category_data",处的变量

更新代码以发送变量

 $.ajax({
                type: "POST",
                url: "/clinical/bbr-category-configuration",
                data: category_data, //change here
                dataType: "json",
                success: function (response){
//...

【讨论】:

  • 感谢您指出这一点,去掉了引号,但我仍然无法添加
  • @STGSH 请求到达$category-&gt;save(); 吗?
  • 对不起,我刚才忘了关闭它,原来我的 pk 没有设置为自动递增,所以函数正在插入 null。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-12-05
  • 1970-01-01
  • 2014-09-10
  • 2021-11-06
  • 2016-06-05
  • 2017-01-03
  • 2020-01-02
  • 1970-01-01
相关资源
最近更新 更多