【问题标题】:Add a training after payment付款后添加培训
【发布时间】:2019-07-06 15:20:36
【问题描述】:

我有 3 个表单,第一个是 students 表单,有 2 个字段(姓名,名字)

然后,我们得到了带有 3 个字段(date_encoding、price、fk_student)的 payments 表单

最后,最后一个表单 trainings 包含 3 个字段(date_sitting、fk_student、fk_payment)。

我的问题是 trainings 表格,我可以在不支付学生费用的情况下创建新记录。

是否可以在培训表格中阻止带有错误消息的记录?

这里是我的代码的想法。

public function store(Request $request)
    {
        $request->validate([
                'date_sitting' => 'required|date',
                'fk_student' => 'required',
                'fk_payment' => 'required'

        ]);

        $exists = Training::where('date_sitting', $request->get('date_sitting'))->where('fk_student', $request->get('fk_student'))->where('fk_payment', $request->get('fk_payment'))->count();

       if (!$exists){
            Training::create($request->all());
            return redirect()->route('trainings.index')
                ->with('success', 'new data created successfully');
        }

        else{
            return redirect()->route('trainings.index')
                ->with('error', 'duplicate');

        }   
    }

【问题讨论】:

    标签: laravel forms laravel-5


    【解决方案1】:

    当然 - 只需在创建块中添加一个 if-check。如果用户没有付款,请不要创建并返回错误消息。您可以通过重定向来执行此操作,或者您甚至可以通过 AJAX 进行单独检查以查看是否有付款,类似于我在下面添加的 $payment 上的 if-check。

    但是,为了保持简单并继续使用它,如下所示:

    if (!$exists){
            // Is there a payment for the student trying to create a training?
    
            $payment = Payment::where('fk_student', $request->get('fk_student'))->first()
    
            // You may wish to add some kind of date check to see if they paid for a specific training
    
            if(!isset($payment)){ // No payment = block creation and return error msg.
                return redirect()->route('trainings.index')
                ->with('error', 'No Payment, no training for you!');
            }
            else{
                Training::create($request->all());
                return redirect()->route('trainings.index')
                    ->with('success', 'new data created successfully');
            }
        }
    

    【讨论】:

    • 感谢您的帮助...但是我有一条错误消息syntax error, unexpected 'if' (T_IF) ??也许是if(!isset($payment)){ ??
    • 不,我忘记了上面一行中 first() 之后的分号。应该是->first(); 试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多